遇到一个比较奇葩的需求,输入文字的时候不能输入表情符号,但是现在苹果支持新的Unicode标准,本身就有一堆的emoji表情。没办法,只能在输入框上做文章,输入的时候过滤掉emoji表情。关键的地方在于过滤方法,下面是扩展NSString的过滤方法:
// 检查字符串是否包含emoji
- (BOOL)containsEmoji
{
__block BOOL contain = NO;
[self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
if ([substring isEmoji]) {
contain = YES;
*stop = YES;
}
}];
return contain;
}
// 检查一个‘字符’是否是emoji表情
- (BOOL)isEmoji
{
if (self.length <= 0) {
return NO;
}
unichar first = [self characterAtIndex:0];
switch (self.length) {
case 1:
{
if (first == 0xa9 || first == 0xae || first == 0x2122 ||
first == 0x3030 || (first >= 0x25b6 && first <= 0x27bf) ||
first == 0x2328 || (first >= 0x23e9 && first <= 0x23fa)) {
return YES;
}
}
break;
case 2:
{
unichar c = [self characterAtIndex:1];
if (c == 0xfe0f) {
if (first >= 0x203c && first <= 0x3299) {
return YES;
}
}
if (first >= 0xd83c && first <= 0xd83e) {
return YES;
}
}
break;
case 3:
{
unichar c = [self characterAtIndex:1];
if (c == 0xfe0f) {
if (first >= 0x23 && first <= 0x39) {
return YES;
}
}
else if (c == 0xd83c) {
if (first == 0x26f9 || first == 0x261d || (first >= 0x270a && first <= 0x270d)) {
return YES;
}
}
if (first == 0xd83c) {
return YES;
}
}
break;
case 4:
{
unichar c = [self characterAtIndex:1];
if (c == 0xd83c) {
if (first == 0x261d || first == 0x270c) {
return YES;
}
}
if (first >= 0xd83c && first <= 0xd83e) {
return YES;
}
}
break;
case 5:
{
if (first == 0xd83d) {
return YES;
}
}
break;
case 8:
case 11:
{
if (first == 0xd83d) {
return YES;
}
}
break;
default:
break;
}
return NO;
}
具体过滤过程比较简单:
1、监听UITextFieldTextDidChangeNotification(UITextField)或者UITextViewTextDidChangeNotification(UITextView);
2、记录lastText,在监听反馈中判断新输入的string是否存在emoji,是的话用lastText替换UITextField或者UITextView的内容,达到不输入emoji的目的,否则更新lastText为当前UITextField或者UITextView的内容。
最后效果如下:
过滤表情符号.gif
用法很简单:只用设置一个属性即可:
textField.shouldAvoidEmoji =YES;
textView.shouldAvoidEmoji =YES;
更新,更好的办法在这里
1、如果你只想输入英文,不用输入中文,那么过滤表情符号的话很简单:
textField.keyboardType=UIKeyboardTypeASCIICapable;
2、如果你想输入中文,但是不想输入表情符号,那么可以实现代理方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField isFirstResponder])
{
if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage])
{
return NO;
}
}
return YES;
}
参考:http://stackoverflow.com/questions/25861468/how-to-disable-ios-8-emoji-keyboard
网友评论
这里了 知道为什么吗?