if self.tf.text?.characters.count > 4 {
Tool.alertUser("昵称最多4个汉字,或者8个字符;数字,字母占一个字符,汉字占2个字符")
return
}
汉字最多4个,但是有人用英文名,只有4个字母明显不够,这咋办?
怪我咯2017-04-18 09:26:15
var length = 0
for char in nickNameTF.text!.characters {
// 判断是否中文,是中文+2 ,不是+1
length += "\(char)".lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 ? 2 : 1
}
if length > 8 {
Tool.alertUser("字数限制为4个汉字或者8个字符;汉字算2个字符,字母、数字算1个字符")
return
}
高洛峰2017-04-18 09:26:15
First of all, a Chinese character does not necessarily occupy 2 bytes.
Secondly, you can try to control the length through String().utf8.count
.
Finally, you can also control it through regular expressions.
PHP中文网2017-04-18 09:26:15
I feel that the problem of the question should be solved like this. Although Chinese characters may occupy 3 characters, we "think" it is two characters. The purpose is to control the length of Chinese and English nicknames, not for the length of utf8
So we should judge if ( a > ; 0x4e00 && a < 0x9fff){Then it’s Chinese, counting two characters}
But it’s not so laborious at the moment, just limit it to a unified value, for example, 10 is good