1、如果是 UITextField ,在 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 代理方法中获取用户输入的文本,即 string。
2、如果是 UITextView,在 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool 代理方法中获取用户输入的文本,即 text 。
3、获取到用户输入的文本后,调用下面的 isEmoji() 方法就可以判断了。
public extension String {
/// 判断是否包含Emoji表情
func isEmoji() -> Bool {
let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
guard !numbers.contains(self) else {
return false
}
let scalars = self.unicodeScalars.map { $0.value }
for element in scalars {
if let scalar = Unicode.Scalar.init(element){
if #available(iOS 10.2, *) {
if scalar.properties.isEmoji {
return true
}
}
}
}
return false
}
}