UI.InputField获得焦点时如何禁用SelectAll()文本?

rjt*_*jth 2 c# unity-game-engine

UI InputField在获得焦点时会突出显示其中的所有文本。我想将插入符号移动到文本的末尾,以便用户可以继续在其中写入文本。目前,我有一个可以解决问题的hack解决方案,但是突出显示文本还有很短的时间。这是我的技巧:

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class TextFieldBehaviour : MonoBehaviour, ISelectHandler
{
    private InputField inputField;
    private bool isCaretPositionReset = false;

    void Start()
    {
        inputField = gameObject.GetComponent<InputField>();
    }

    public void OnSelect (BaseEventData eventData) 
    {
        isCaretPositionReset = false;
    }

    void Update()
    {
        if(inputField.isFocused == true && isCaretPositionReset == false)
        {
            inputField.caretPosition = inputField.text.Length;
            isCaretPositionReset = true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也在检查InputField 的源代码。但是我在创建没有SelectAll()函数的自定义代码时遇到了麻烦。由于的保护水平,我得到了很多错误UnityEngine.UI.SetPropertyUtility

Pro*_*mer 5

有一个技巧可以禁用短时突出显示文本。我设法在没有该Update()功能的情况下重做此操作。

1。获取颜色InputField.selectionColor。将其alpha设置为0

2。将新颜色从#1应用于InputField

3等待一帧。您必须因为Unity插入符等待一帧出现。

4。更改InputField插入标记的位置。

5。InputField.selectionColoralpha更改回1

public class TextFieldBehaviour : MonoBehaviour, ISelectHandler
{
    private InputField inputField;
    private bool isCaretPositionReset = false;

    void Start()
    {
        inputField = gameObject.GetComponent<InputField>();
    }

    public void OnSelect(BaseEventData eventData)
    {
        StartCoroutine(disableHighlight());
    }

    IEnumerator disableHighlight()
    {
        Debug.Log("Selected!");

        //Get original selection color
        Color originalTextColor = inputField.selectionColor;
        //Remove alpha
        originalTextColor.a = 0f;

        //Apply new selection color without alpha
        inputField.selectionColor = originalTextColor;

        //Wait one Frame(MUST DO THIS!)
        yield return null;

        //Change the caret pos to the end of the text
        inputField.caretPosition = inputField.text.Length;

        //Return alpha
        originalTextColor.a = 1f;

        //Apply new selection color with alpha
        inputField.selectionColor = originalTextColor;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意

将插入符号移至文本末尾的最佳方法是使用MoveTextEnd函数而不是inputField.caretPositioninputField.caretPosition如果您的文字较长,则会发现一个bug 。

如果您对此很在意inputField.caretPosition = inputField.text.Length;,请inputField.MoveTextEnd(false);在上面的代码中替换为。