【问题标题】:How to disable text highlighting when tapping input field?点击输入字段时如何禁用文本突出显示?
【发布时间】:2019-09-16 01:21:27
【问题描述】:

我知道以前有人问过这个问题,但似乎没有一个解决方案适用于移动设备。我找到的解决方案here 在我的 PC 上完美运行,但不幸的是在我的平板电脑上却不行。我已经对解决方案发表了评论,看看他们是否可以提供帮助,但似乎他们已经一年多了。因此,我在这里碰碰运气,看看是否有人知道如何让他们的解决方案在移动设备上运行?

这是我的代码:

using System.Collections;
using System.Collections.Generic;
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)
    {
         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;

        if (inputField.touchScreenKeyboard.canSetSelection)
            inputField.touchScreenKeyboard.selection = new RangeInt(0, 0);
    }
}

【问题讨论】:

  • 它工作戴夫!!!!非常感谢你!!!我会将您的帖子标记为答案并奖励您 50+ 声望点!谢谢!

标签: c# unity3d input user-input mobile-devices


【解决方案1】:

如果您正在撰写有关本机屏幕键盘的文章,您可以尝试this:

if (inputField.touchScreenKeyboard != null && inputField.touchScreenKeyboard.active && inputField.touchScreenKeyboard.canSetSelection)
    inputField.touchScreenKeyboard.selection = new RangeInt(0, 0);

RangeInt的参数是选择的起始位置和长度;

请注意,并非所有平台都支持此功能。有关 TouchScreenKeyboard 的所有功能,请参阅文档 here 和 here。

【讨论】:

  • 非常感谢您的评论。您知道您的解决方案将如何插入我在帖子中链接的代码吗?谢谢你:)
  • 把这段代码代替OnSelect方法中的启动StartCoroutine。如果这对您不起作用,请告诉我,我会自己尝试:)
  • 谢谢@Dave。我已将代码放在您所说的位置,但出现错误消息“TouchScreenKeyboard 不包含 'canSetSelection' 的定义?
  • 我可以看到这个选项在 Unity 2018 及更高版本中。你有旧版本吗?
  • 好的,我已经在 Unity 2019 中打开它。我现在收到以下错误:非静态字段、方法或属性“TouchScreenKeyboard.canSetSelection”需要对象引用
猜你喜欢
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 2014-04-03
  • 2013-07-05
  • 1970-01-01
  • 2019-01-13
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多