删除表情符号错误

时间:2016-11-12 20:08:04

标签: ios swift uitextfield uitextfielddelegate

我按照此链接Find out if Character in String is emoji?尝试使用表情符号来限制文本字段的字符数量。根据这个链接,我必须根据他们的字形计算表情符号并且一切正常,除了一个小错误,当我的字形数量达到时,它不再让我删除字符串。

这里是使用UITextField Delegate处理字符限制的代码

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

var canEditString : Bool = false

if textField == self.descTxtField {

    // Description Text Field
    if textField.text != nil || textField.text != "" {

        let currentString = textField.text
        if (currentString?.containsEmoji)! {
            print("I have an emoji")
            let glyphCount = currentString!.glyphCount
            print(glyphCount)
            canEditString = glyphCount <= descriptionLimit
        }else {
            print("I have no emoji's")
            let currentCharacterCount = textField.text?.characters.count ?? 0
            //print(currentCharacterCount)
            if (range.length + range.location > currentCharacterCount){
                return false
            }
            let newLength = currentCharacterCount + string.characters.count - range.length
            canEditString = newLength <= descriptionLimit
        }
    }
    return canEditString


} else {

    // Number Text Field
    let currentCharacterCount = textField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    return newLength <= numberLimit
}
}

1 个答案:

答案 0 :(得分:0)

String Manifesto

Swift 4

Emojis现在的字符数为1,因此可以更轻松地跟踪字符串中的字符数。