unity-UIInput自定义限制输入字符
UIInput组件如下图所示
UIInput可以用于创建输入框,它自带6种限制方式,如下图所示
最后一种Alphabet Int Chinese是我自定义的,用于限制输入字母,数字,汉字,比如昵称,就可以使用这种设定
自定义限制输入需要修改UIInput的代码
首先,找到Validation这个属性
1 public enum Validation 2 { 3 None, 4 Integer, 5 Float, 6 Alphanumeric, 7 Username, 8 Name, 9 AlphabetIntChinese, // 自定义 10 }
在其中加入我们自定义类型的名字,我这里加的是AlphabetIntChinese
找到Validate这个函数
1 protected char Validate (string text, int pos, char ch) 2 { 3 // Validation is disabled 4 if (validation == Validation.None || !enabled) return ch; 5 6 if (validation == Validation.Integer) 7 { 8 // Integer number validation 9 if (ch >= '0' && ch <= '9') return ch; 10 if (ch == '-' && pos == 0 && !text.Contains("-")) return ch; 11 } 12 else if (validation == Validation.Float) 13 { 14 // Floating-point number 15 if (ch >= '0' && ch <= '9') return ch; 16 if (ch == '-' && pos == 0 && !text.Contains("-")) return ch; 17 if (ch == '.' && !text.Contains(".")) return ch; 18 } 19 else if (validation == Validation.Alphanumeric) 20 { 21 // All alphanumeric characters 22 if (ch >= 'A' && ch <= 'Z') return ch; 23 if (ch >= 'a' && ch <= 'z') return ch; 24 if (ch >= '0' && ch <= '9') return ch; 25 } 26 else if (validation == Validation.Username) 27 { 28 // Lowercase and numbers 29 if (ch >= 'A' && ch <= 'Z') return (char)(ch - 'A' + 'a'); 30 if (ch >= 'a' && ch <= 'z') return ch; 31 if (ch >= '0' && ch <= '9') return ch; 32 } 33 else if (validation == Validation.Name) 34 { 35 char lastChar = (text.Length > 0) ? text[Mathf.Clamp(pos, 0, text.Length - 1)] : ' '; 36 char nextChar = (text.Length > 0) ? text[Mathf.Clamp(pos + 1, 0, text.Length - 1)] : '\n'; 37 38 if (ch >= 'a' && ch <= 'z') 39 { 40 // Space followed by a letter -- make sure it's capitalized 41 if (lastChar == ' ') return (char)(ch - 'a' + 'A'); 42 return ch; 43 } 44 else if (ch >= 'A' && ch <= 'Z') 45 { 46 // Uppercase letters are only allowed after spaces (and apostrophes) 47 if (lastChar != ' ' && lastChar != '\'') return (char)(ch - 'A' + 'a'); 48 return ch; 49 } 50 else if (ch == '\'') 51 { 52 // Don't allow more than one apostrophe 53 if (lastChar != ' ' && lastChar != '\'' && nextChar != '\'' && !text.Contains("'")) return ch; 54 } 55 else if (ch == ' ') 56 { 57 // Don't allow more than one space in a row 58 if (lastChar != ' ' && lastChar != '\'' && nextChar != ' ' && nextChar != '\'') return ch; 59 } 60 } 61 //自定义,只允许输入字母数字汉字 62 else if (validation == Validation.AlphabetIntChinese) 63 { 64 if (ch>=0x4e00 && ch<=0x9fa5) return ch;//这个主要是汉字的范围 65 if (ch >= 'A' && ch <= 'Z') return ch; 66 if (ch >= 'a' && ch <= 'z') return ch; 67 if (ch >= '0' && ch <= '9') return ch; 68 } 69 return (char)0; 70 }
在函数最后加上我们所需的类型即可
也可以从此函数中看出,原设类型都是哪种限制
以上做好后,在UIInput组件中Validate属性选择我们自定义的属性即可