ios中UITextfield中禁止输入Emoji

时间:2022-11-06 23:42:08

在iOS中,可以即使可以禁止使用Emoji键盘,但是也可以通过键盘打出Emoji,在实际开发中,可能需要在输入框中禁止使用输入Emoji,可以通过以下的方式来对输入内容进行过滤,

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    UITextField *searchTextField = [[UITextFieldalloc]initWithFrame:CGRectMake(50,50, 200 ,25)];

    searchTextField.backgroundColor = [UIColorwhiteColor];

    self.view.backgroundColor = [UIColorlightGrayColor];

    [searchTextField addTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];

    [self.viewaddSubview:searchTextField];

}


- (void)textFieldDidChange:(UITextField *)textField {

    NSRegularExpression *regularExpression = [NSRegularExpressionregularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"options:0error:nil];

    NSString *noEmojiStr = [regularExpressionstringByReplacingMatchesInString:textField.textoptions:0range:NSMakeRange(0, textField.text.length)withTemplate:@""];

    

    if (![noEmojiStrisEqualToString:textField.text]) {

        textField.text = noEmojiStr;

    }

}