删除表情符号错误

Deleting Emoji Bug

我按照此 link 尝试限制我的文本字段的字符数量,即使使用表情符号也是如此。根据这个 link,我必须根据表情符号的字形来计算表情符号,除了一个小错误外,一切正常,当我的字形计数达到时,它不再让我删除字符串。

这是使用 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
}
}

String Manifesto

Swift 4

表情符号现在的字符数为 1,这使得跟踪字符串中的字符数变得更加容易。