Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

InputField Highlighting / MoveTextEnd

Discussion in 'Unity UI (uGUI) & TextMesh Pro' started by Yukichu, Mar 31, 2015.

  1. Yukichu

    Yukichu

    Joined:
    Apr 2, 2013
    Posts:
    417
    I must be doing something awfully wrong.

    I have an InputField. I want to give it focus via code. No problem. I want to give it focus and already have text in there. Okay, I can do that. Problem is, all the text is highlighted as it is newly selected. Well, I suppose I can use MoveTextEnd(true) to move the caret.

    I cannot make this work on the same frame as the text is set / selection of InputField occurs.

    If I add a coroutine to wait one frame, it will work.

    Code (csharp):
    1.  
    2. if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
    3. {
    4.     selected = EventSystem.current.currentSelectedGameObject;
    5.  
    6.     if (!inputField.gameObject.Equals(selected))
    7.     {
    8.         EventSystem.current.SetSelectedGameObject(inputField.gameObject, null);
    9.         inputField.ActivateInputField();
    10.         inputField.text = "SOMETEXT";
    11.  
    12.         // this doesn't work same frame???
    13.         //inputField.MoveTextEnd(true);
    14.  
    15.         StartCoroutine(WaitForNextFrame());
    16.     }
    17. }
    WaitForNextFrame just waits 1 frame, then does the inputField.MoveToEnd(true). It works, but is there an better/correct way to do this on the same frame?
     
  2. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,629
    You may need to add that code to LateUpdate, simply due to the way that UI is managed. The "Selected" UI element may not be updated till after the frame is rendered.
     
  3. chrismarch

    chrismarch

    Joined:
    Jul 24, 2013
    Posts:
    318
    I created a subclass of InputField, and in its LateUpdate, I call MoveToEnd after base.LateUpdate. The class knows to do this by setting a flag in an override of OnSelect (which also calls base.OnSelect). This will MoveToEnd on the same frame that InputField calls OnFocus > SelectAll internally from LateUpdate
     
  4. nxAAA

    nxAAA

    Joined:
    Jun 30, 2014
    Posts:
    2
    Could you please provide an example showing how it would look like? :eek:
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,695
    If you look into the InputField code, there is a part where it selects all text when it gains focus. You can block that out if you need to and keep it from selecting all.
     
    DDeathlonger likes this.
  6. yunhan0

    yunhan0

    Joined:
    Aug 18, 2016
    Posts:
    5