Search code examples
c#unity-game-engineinputuser-inputmobile-devices

How to disable text highlighting when tapping input field?


I know this question has been asked before but none of the solutions seem to work on mobile devices. The solution I found here worked perfectly on my PC but not on my tablet unfortunately. I've commented on the solution to see if they can help but it seems they haven't been on SO for over a year. I'm therefore trying my luck here to see if anyone know how to get their solution working on mobile devices?

This is my code:

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);
    }
}

Solution

  • If you are writing about native on-screen keyboards you can try this:

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

    The parameters of the RangeInt are the start position and length of the selection;

    Keep in mind this is not supported on all platforms. For all of the TouchScreenKeyboard functionality see the docs here and here.