Reputation: 495
I have an issue with my UITextView character limit where the count double, triple, or quadruple counts emoji. I want emoji to count as 1 character, the way they do in the Twitter iOS app. Here is the code I have in my shouldChangeTextInRange
method
let characters = textView.text.characters.count + (text.characters.count - range.length)
if characters <= self.characterLimit {
// update character limit label as we type
self.characterLimitLabel.text = String(characters) + "/" + String(self.characterLimit)
return true
} else {
return false
}
What should I change to produce the proper result when accounting for emoji?
Upvotes: 2
Views: 1315
Reputation: 852
Use NSString length instead of String count
let newString: NSString = currentString.replacingCharacters(in: range, with: text) as NSString
let characters = newString.length
if characters <= self.characterLimit {
// update character limit label as we type
self.characterLimitLabel.text = String(characters) + "/" + String(self.characterLimit)
return true
} else {
return false
}
Upvotes: 1
Reputation: 2237
I don't think it's going to be an easy solution... You will have to check the unicode values to see if each character is an emoji. You will have to hard code those cases, and then you will have to update them every time new emojis are released. My recommendation is that you should just forget about emojis costing more characters... If you want more information, there's a github repo that can check for emojis pretty simply.. but then again, it may become outdated (if not already outdated).
https://github.com/woxtu/NSString-RemoveEmoji
Upvotes: 1