1
我跟着這個鏈接Find out if Character in String is emoji?嘗試限制我的文本字段的字符數量,即使使用表情符號。根據這個鏈接,我必須根據他們的字形來計算表情符號,除了一個小錯誤之外,一切正在工作,當我的字形計數達到時,它不會讓我再刪除字符串。刪除Emoji Bug
下面的代碼使用的UITextField代表
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
}
}
你應該使用'guard'而不是'let'來減少厄運的金字塔 – Alexander
'range.length'和'string.characters.count'不兼容:*第一個計數UTF-16代碼單元而後者計數擴展了Unicode字形集羣。看看http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index的各種答案。 –
你可能感興趣[如何知道兩個表情符號是否會顯示爲一個表情符號?](http://stackoverflow.com/questions/39104152/how-to-know-if-two-emojis-will-be-顯示爲一個表情符號) –