很多时候策划会要求输入框限制长度,一般来讲,按字节数算比按字符串长度算更合理,在UTF-8编码格式下,通常汉字占3个字节,英文字母占1个字节,如果是按长度算的话,界面排版上会很丑。
public InputField inputField;
int MaxLimit = 18;
void Start()
{
inputField.onValidateInput = _OnValidateInput;
}
char _OnValidateInput(string text, int charIndex, char addedChar)
{
if (System.Text.Encoding.UTF8.GetBytes(text + addedChar).Length > MaxLimit)
{
return '\0'; //返回空
}
return addedChar;
}