Unity NGUI input 长度与输入类型设置
Unity NGUI input 输入长度与输入类型设置,可限制输入的长度和输入的类型
操作方法
- 01
UIInput 脚本预览,找到characterLimit属性,设置指定长度值UIInput.characterLimit=6;
- 02
UIInput 脚本预览,找到validation属性,定义如下 public enum Validation { None, Integer, Float, Alphanumeric, Username, Name, } ,设置只能输入数字UIInput.validation=UIInput.Validation.Integer
- 03
限制输入类型内部实现方法,可参考 protected char Validate (string text, int pos, char ch) { // Validation is disabled if (validation == Validation.None || !enabled) return ch; if (validation == Validation.Integer) { // Integer number validation if (ch >= '0' && ch <= '9') return ch; if (ch == '-' && pos == 0 && !text.Contains("-")) return ch; } else if (validation == Validation.Float) { // Floating-point number if (ch >= '0' && ch <= '9') return ch; if (ch == '-' && pos == 0 && !text.Contains("-")) return ch; if (ch == '.' && !text.Contains(".")) return ch; } else if (validation == Validation.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 (validation == Validation.Username) { // Lowercase and numbers if (ch >= 'A' && ch <= 'Z') return (char)(ch - 'A' + 'a'); if (ch >= 'a' && ch <= 'z') return ch; if (ch >= '0' && ch <= '9') return ch; } else if (validation == Validation.Name) { char lastChar = (text.Length > 0) ? text[Mathf.Clamp(pos, 0, text.Length - 1)] : ' '; char nextChar = (text.Length > 0) ? text[Mathf.Clamp(pos + 1, 0, text.Length - 1)] : '\n'; if (ch >= 'a' && ch <= 'z') { // Space followed by a letter -- make sure it's capitalized if (lastChar == ' ') return (char)(ch - 'a' + 'A'); return ch; } else if (ch >= 'A' && ch <= 'Z') { // Uppercase letters are only allowed after spaces (and apostrophes) if (lastChar != ' ' && lastChar != '\'') return (char)(ch - 'A' + 'a'); return ch; } else if (ch == '\'') { // Don't allow more than one apostrophe if (lastChar != ' ' && lastChar != '\'' && nextChar != '\'' && !text.Contains("'")) return ch; } else if (ch == ' ') { // Don't allow more than one space in a row if (lastChar != ' ' && lastChar != '\'' && nextChar != ' ' && nextChar != '\'') return ch; } } return (char)0; }