ios - Swift : textField可输入的长度为4个汉字或者8个字符。咋判断
大家讲道理
大家讲道理 2017-04-18 09:24:15
0
4
342
        if self.tf.text?.characters.count > 4 {
            Tool.alertUser("昵称最多4个汉字,或者8个字符;数字,字母占一个字符,汉字占2个字符")
            return
        }

汉字最多4个,但是有人用英文名,只有4个字母明显不够,这咋办?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
刘奇
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
}
小葫芦
  • 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.

迷茫

I have seen many input boxes that are counted in bytes.

洪涛

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 &gt ; 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template