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

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 disabled
	if (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 validation
		if (ch >= '0' && ch <= '9') return ch;
		if (ch == '-' && text.Length == 0) return ch;
	}
	else if (logic == Validation.Float)
	{
		// Floating-point number
		if (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 characters
		if (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 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 (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 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 != '\'' && !text.Contains("'")) return ch;
		}
		else if (ch == ' ')
		{
			// Don't allow more than one space in a row
			if (lastChar != ' ' && lastChar != '\'') return ch;
		}
	}
	return (char)0;
}

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




阅读更多
个人分类: Unity3d
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭