How to disable SelectAll() text of InputField OnFocus()?
The UI InputField when it gets focus highlights all text inside. I would like to move the caret to the end of the text so the user can keep writing the text within. Currently I have a hack solution, which works, however there it is still a short moment when the text is highlighted. Here is my 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;
}
}
}
I was also checking out the source code of InputField. But I have trouble trouble creating a custom one without the SelectAll() function. I am getting a bunch of errors due to the protection level of the UnityEngine.UI.SetPropertyUtility
.
Answer by rjth · Jan 05, 2017 at 03:16 PM
Okay so I've figured it out. I needed to inherit from the original InputField and extend it with the necessary functionality. Here is the working script:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class CustomInputField : InputField
{
new public bool Focused = false;
new public bool Deactivated = false;
new public void ActivateInputField()
{
Focused = true;
base.ActivateInputField();
}
public override void OnDeselect(BaseEventData eventData)
{
Deactivated = true;
DeactivateInputField();
base.OnDeselect(eventData);
}
public override void OnPointerClick(PointerEventData eventData)
{
if(Deactivated)
{
MoveTextEnd(true);
Deactivated = false;
}
base.OnPointerClick(eventData);
}
protected override void LateUpdate()
{
base.LateUpdate();
if(Focused)
{
MoveTextEnd(true);
Focused = false;
}
}
}
I thought i doesn't work, but it was just because i was absent$$anonymous$$dedly use "ActivateInputField()" from "InputFIeld"-reference, ins$$anonymous$$d of "CustomInputField"-reference, geez...
As on stackoverflow-theme mentioned, its still have problems with short (1 frame probably?) highlighting of text when you use $$anonymous$$ouse to click on this InputField, but it works perfectly in case you need to set focus just programmatically using ActivateInputField() which is exactly what i need. Thanks!
P.S. I will rename "ActivateInputField()" to "ActivateInputFieldWithoutSelectAll()" and remove "new" on my side to avoid such stupid situations as I described above :)