search

Home  >  Q&A  >  body text

ios - Swift : textField可输入的长度为4个汉字或者8个字符。咋判断

        if self.tf.text?.characters.count > 4 {
            Tool.alertUser("昵称最多4个汉字,或者8个字符;数字,字母占一个字符,汉字占2个字符")
            return
        }

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

大家讲道理大家讲道理2892 days ago350

reply all(4)I'll reply

  • 怪我咯

    怪我咯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
    }

    reply
    0
  • 高洛峰

    高洛峰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.

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:26:15

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

    reply
    0
  • PHP中文网

    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

    reply
    0
  • Cancelreply