又遇到輸入框輸入表情的情況了获询,之前寫了一篇文章“UITextView/UITextField檢測并過濾Emoji表情符號(hào)”http://www.reibang.com/p/90d68e7e5d53,但是總覺得那兩種方式都各有弊端带猴,這次又遇到之后泻云,仔細(xì)考慮了下之后,想到了用兩種方式組合在一起使用香伴,測試結(jié)果暫時(shí)沒什么問題,在輸入時(shí)就限制了emoji表情輸入,完全符合需求。在此貼出代碼麻裳,如果有什么問題口蝠,歡迎指正器钟!
@interface JQTestViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic, assign) NSInteger textLocation;//這里聲明一個(gè)全局屬性,用來記錄輸入位置
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.textField.delegate = self;
[self.textField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];//注意:textFied沒有textFieldDidChanged代理方法妙蔗,但是有UITextFieldTextDidChangeNotification通知傲霸,這里添加通知方法,textView有textFieldDidChanged代理方法眉反,下面用法一樣
}
#pragma mark-- UITextFieldDelegate
//在輸入時(shí)昙啄,調(diào)用下面那個(gè)方法來判斷輸入的字符串是否含有表情
- (void)textFieldDidChanged:(UITextField *)textField
{
if (textField.text.length > 20) {
textField.text = [textField.text substringToIndex:20];
[self showMessage:@"不可超過20字!"];
}else {
if (self.textLocation == -1) {
NSLog(@"輸入不含emoji表情");
}else {
NSLog(@"輸入含emoji表情");
//截取emoji表情前
textField.text = [textField.text substringToIndex:self.textLocation];
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(@"location-->>%lu",(unsigned long)range.location);
NSLog(@"replacementString-->>%@",string);
//禁止輸入emoji表情
if ([self stringContainsEmoji:string]) {
self.textLocation = range.location;
}else {
self.textLocation = -1;
}
return YES;
}
//表情符號(hào)的判斷
- (BOOL)stringContainsEmoji:(NSString *)string {
__block BOOL returnValue = NO;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:0];
if (0xd800 <= hs && hs <= 0xdbff) {
if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f77f) {
returnValue = YES;
}
}
} else if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3) {
returnValue = YES;
}
} else {
if (0x2100 <= hs && hs <= 0x27ff) {
returnValue = YES;
} else if (0x2B05 <= hs && hs <= 0x2b07) {
returnValue = YES;
} else if (0x2934 <= hs && hs <= 0x2935) {
returnValue = YES;
} else if (0x3297 <= hs && hs <= 0x3299) {
returnValue = YES;
} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
returnValue = YES;
}
}
}];
return returnValue;
}