NGUI UIInput屏蔽特殊字符(允许输入汉字)

来源:互联网 发布:淘宝助理 菜鸟打印 编辑:程序博客网 时间:2024/06/07 01:02

2014/12/29更新:

现在的新版本已经找不到UIInputValidator这个脚本了,官方直接把功能集成到了UIInput里面,大家可以编辑UIInput达到相同的目的,对应修改UIInput的Validation属性即可。

-----------------------------------------------------------------------------------------------------------------------

可以用组件UIInputValidator达到预期效果,不过为了支持汉字输入,需做一定的修改

修改UIInpurtValidator的代码如下:


首先是在枚举Validation里添加一种过滤规则

public enum Validation{<span style="white-space:pre"></span>None,Integer,Float,Alphanumeric,Username,Name,<span style="color:#ff0000">Chinese,//这个是新添加的</span>}

然后修改Validate方法如下

char Validate (string text, char ch){// Validation is disabledif (logic == Validation.None || !enabled) return ch;<span style="color:#ff0000">if (logic == Validation.Chinese){if (ch>=0x4e00 && ch<=0x9fa5) return ch;//这个主要是汉字的范围if (ch >= 'A' && ch <= 'Z') return ch;if (ch >= 'a' && ch <= 'z') return ch;if (ch >= '0' && ch <= '9') return ch;}else</span> if (logic == Validation.Integer){// Integer number validationif (ch >= '0' && ch <= '9') return ch;if (ch == '-' && text.Length == 0) return ch;}else if (logic == Validation.Float){// Floating-point numberif (ch >= '0' && ch <= '9') return ch;if (ch == '-' && text.Length == 0) return ch;if (ch == '.' && !text.Contains(".")) return ch;}else if (logic == Validation.Alphanumeric){// All alphanumeric charactersif (ch >= 'A' && ch <= 'Z') return ch;if (ch >= 'a' && ch <= 'z') return ch;if (ch >= '0' && ch <= '9') return ch;}else if (logic == Validation.Username){// Lowercase and numbersif (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 (logic == Validation.Name){char lastChar = (text.Length > 0) ? text[text.Length - 1] : ' ';if (ch >= 'a' && ch <= 'z'){// Space followed by a letter -- make sure it's capitalizedif (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 apostropheif (lastChar != ' ' && lastChar != '\'' && !text.Contains("'")) return ch;}else if (ch == ' '){// Don't allow more than one space in a rowif (lastChar != ' ' && lastChar != '\'') return ch;}}return (char)0;}

红色部分为新添加的代码,这样子就可以在u3d编辑器里设置logic的值为Chinese就可以了
如果有需求需要允许一些特殊字符,直接修改Validate方法就可以了




原创粉丝点击