[英]How to override default behavior of END button in InputField, in Unity?
我正在嘗試在 Unity 中創建一個簡單的文本編輯器。
現在,我正在嘗試覆蓋標准的End鍵盤鍵功能。
我使用“新”UI 系統和InputField
作為文本編輯器。 它啟用了多行。 通常,當您點擊End (在普通物理鍵盤上)時,當焦點位於InputField
,插入符號會到達整個TextField
的末尾。 我希望它只到當前行的末尾。 基本上我想要與 Notepad++ 等普通文本編輯器相同的功能。
到目前為止,我在InputField
上有一個腳本,如下所示:
public InputField editor; // This is the InputField
void Update()
{
if (Input.GetKeyDown(KeyCode.End))
{
string code = editor.text;
int caretPos = editor.caretPosition;
int newLineIndex = FindEndOfLine(code, caretPos);
editor.caretPosition = newLineIndex;
}
}
int FindEndOfLine(string text, int startIndex)
{
for (int i = startIndex; i < text.Length; i++)
{
Debug.Log(text[i]);
if (text[i] == '\n')
{
Debug.Log("FOUND IT: " + i);
return i;
}
}
return text.Length;
}
如果我將它用於另一個鍵,比如KeyCode.Y
,那么它工作得很好。 它找到正確的插入符號位置並將插入符號移動到那個位置。 但是,它也會打印字符Y
。
當我使用KeyCode.End
並點擊End鍵時,它只會轉到整個TextField
的末尾。 所以我認為我的代碼有效,但它在我的腳本執行后執行正常的End鍵功能。
如何防止這種默認行為? 我已經谷歌搜索了 25 分鍾。
請嘗試以下解決方案。 您應該繼承InputField
類,覆蓋Rebuild
方法以保存CaretPosition
並覆蓋LateUpdate
方法以更改End鍵的行為。 當你完成更換InputField
在你的組件GameObject
與CustomInputField
腳本。
using UnityEngine;
using UnityEngine.UI;
public class CustomInputField : InputField
{
private int oldCaretPosition;
public override void Rebuild(CanvasUpdate update)
{
base.Rebuild(update);
oldCaretPosition = caretPosition;
}
protected override void LateUpdate()
{
base.LateUpdate();
if (Input.GetKeyDown(KeyCode.End))
{
int newLineIndex = FindEndOfLine(oldCaretPosition);
caretPosition = newLineIndex;
}
}
private int FindEndOfLine(int startIndex)
{
for (int i = startIndex; i < text.Length; i++)
{
if (text[i] == '\n')
{
return i;
}
}
return text.Length;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.