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屬性選擇我們自定義的屬性即可