(十四)InputField逻辑分析
本文来讲一下InputField实现,本文之所以叫逻辑分析是因为跟作者自己和解了,不再去追求一些细节的实现(其实是脑细胞不够理解不了)。
文字获取通过TouchScreenKeyboard获取。在激活模块时根据需求(比如是否多行,是否只有数字)打开所有键盘,此步操作主要针对触屏设备(苹果、android或者触屏windows)。然后在LateUpdate通过TouchScreenKeyboard.text获取输入文本;通过Input.compositionString获取当前输入(比如汉字是通过字母组合产生,此时获取的为字符)纯粹的字符输入。
在LateUpdate中获取到字符时会进行有效性检查,如下所示:
// Doesn't include dot and @ on purpose! See usage for details.
const string kEmailSpecialCharacters = "!#$%&'*+-/=?^_`{|}~";
protected char Validate(string text, int pos, char ch)
{
// Validation is disabled
if (characterValidation == CharacterValidation.None || !enabled)
return ch;
if (characterValidation == CharacterValidation.Integer || characterValidation == CharacterValidation.Decimal)
{
// Integer and decimal
bool cursorBeforeDash = (pos == 0 && text.Length > 0 && text[0] == '-');
bool dashInSelection = text.Length > 0 && text[0] == '-' && ((caretPositionInternal == 0 && caretSelectPositionInternal > 0) || (caretSelectPositionInternal == 0 && caretPositionInternal > 0));
bool selectionAtStart = caretPositionInternal == 0 || caretSelectPositionInternal == 0;
if (!cursorBeforeDash || dashInSelection)
{
if (ch >= '0' && ch <= '9') return ch;
if (ch == '-' && (pos == 0 || selectionAtStart)) return ch;
if (ch == '.' && characterValidation == CharacterValidation.Decimal && !text.Contains(".")) return ch;
}
}
else if (characterValidation == CharacterValidation.Alphanumeric)
{
// All alphanumeric characters
if (ch >= 'A' && ch <= 'Z') return ch;
if (ch >= 'a' && ch <= 'z') return ch;
if (ch >= '0' && ch <= '9') return ch;
}
else if (characterValidation == CharacterValidation.Name)
{
if (char.IsLetter(ch))
{
// Character following a space should be in uppercase.
if (char.IsLower(ch) && ((pos == 0) || (text[pos - 1] == ' ')))
{
return char.ToUpper(ch);
}
// Character not following a space or an apostrophe should be in lowercase.
if (char.IsUpper