Search Unity

UIElements block input to TextField

Discussion in 'UI Toolkit' started by TJHeuvel-net, Sep 5, 2018.

  1. TJHeuvel-net

    TJHeuvel-net

    Joined:
    Jul 31, 2012
    Posts:
    838
    I'm trying to use the new UIElements API for an editor tool, and i'd like to selectively block key-input. For example i dont want the user to be able to input any space character.

    In the old UI i'd listen to an KeyDown event type and use it, in UIElements i think i have to register an KeyDownEvent callback and call StopPropagation. That doesnt seem to work, tried this via an Manipulator too to no avail. Tried various Capture modes, and StopImmediatePropegation.

    For example:

    Code (csharp):
    1.  
    2.  
    3.     void OnEnable()
    4.     {
    5.         var root = this.GetRootVisualContainer();
    6.  
    7.         root.AddStyleSheetPath("styles");
    8.         var searchBox = new TextField()
    9.         {
    10.             name = "searchBox"
    11.         };
    12.         searchBox.RegisterCallback<KeyDownEvent>(onKeyDown, Capture.Capture);
    13.  
    14.         searchBox.OnTextChanged += onSearchChanged;
    15.         root.Add(searchBox);
    16.     }
    17.  
    18.     private void onKeyDown(KeyDownEvent evt)
    19.     {
    20.         if(evt.keyCode == KeyCode.Space)
    21.         {
    22.             evt.imguiEvent.Use();
    23.             evt.StopPropagation();
    24.             evt.StopImmediatePropagation();
    25.         }
    26.     }
    27.  
    28.  
    Still allows me to insert a space. What am i doing wrong?
     
  2. patrickf

    patrickf

    Unity Technologies

    Joined:
    Oct 24, 2016
    Posts:
    57
    Hi, you need to call evt.PreventDefault(). This will prevent the event default action from being executed, whereas the StopPropagation() will only stop event from propagating in the element tree and executing further event callbacks.
     
    TJHeuvel-net likes this.
  3. benoitd_unity

    benoitd_unity

    Unity Technologies

    Joined:
    Jan 2, 2018
    Posts:
    331
    FYI, we now have a dedicated sub-forums where you can use for all your questions and feedback related to UI Systems Previews.

    Cheers,