1

I followed this link Find out if Character in String is emoji? to try to limit the amount of characters my text field even with emojis. According to this link, I have to count emojis based on their glyphs and everything is working except for one little bug, when my glyph count is reached, it won't let me delete the string anymore.

Here's the code the handle the character limit using 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
}
}
Community
  • 1
  • 1
Mochi
  • 1,059
  • 11
  • 26
  • You should use `guard` rather than `let` to reduce your pyramid of doom a bit – Alexander Nov 12 '16 at 20:12
  • `range.length` and `string.characters.count` are not *compatible:* the first counts UTF-16 code units and the latter counts extended Unicode grapheme clusters. Have a look at the various answers to http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index. – Martin R Nov 12 '16 at 20:17
  • You might be interested in [How to know if two emojis will be displayed as one emoji?](http://stackoverflow.com/questions/39104152/how-to-know-if-two-emojis-will-be-displayed-as-one-emoji) – Martin R Nov 12 '16 at 20:18
  • Thanks for your help @MartinR – Mochi Nov 14 '16 at 08:25

1 Answers1

0

String Manifesto

Swift 4

Emojis now have a character count of 1, making it a lot easier to keep track of character counts in Strings.

Mochi
  • 1,059
  • 11
  • 26