UITextField
self.remarkTextField.delegate = self;
numLim = 20;
#pragma mark - TextFieldDelegate
//限制字数输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.remarkTextField) {
//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
if (range.length == 1 && string.length == 0) {
return YES;
} else if (self.remarkTextField.text.length >= numLim) {
self.remarkTextField.text = [textField.text substringToIndex:numLim];
return NO;
}
}
return YES;
}
/**********过滤表情emoji************/
//添加通知检测UITextField
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText:) name:UITextFieldTextDidChangeNotification object:nil];
//过滤方法
- (void)changeText:(UITextField*)sender{
NSLog(@"没有过滤前输入的字符串===%@",self.remarkTextField.text);
NSString *filterString = [self filterEmoji:self.remarkTextField.text];
NSLog(@"过滤Emoji表情后的字符串===%@",filterString);
self.remarkTextField.text = filterString;
_strLengthLbl.text = [NSString stringWithFormat:@"%lu/%d",_remarkTextField.text.length,numLim];
}
UITextView
//限制字数
- (void)textViewDidChange:(UITextField *)textView{
if (textView.text.length > 20) {
textView.text = [textView.text substringToIndex:20];
}
_strLengthLbl.text = [NSString stringWithFormat:@"%lu/50",textView.text.length];
}
//UITextView有直接可用代理进行控制过滤表情emoji
- (void)textViewDidChange:(UITextView *)textView{
NSLog(@"没有过滤前输入的字符串===%@",textView.text);
NSString *filterString = [self filterEmoji:textView.text];
NSLog(@"过滤Emoji表情后的字符串===%@",filterString);
textView.text = filterString;
}
正则过滤表情
- (NSString *)filterEmoji:(NSString *)text{
if (!text.length) return text;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length])withTemplate:@""];
return modifiedString;
}
限制输入手机号码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *oldText = textField.text;
NSString *newText = [oldText stringByReplacingCharactersInRange:range withString:string];
NSString *numtext = newText.length > 0 || range.length > 0 ? newText : oldText;
if (numtext.length > 10) {
textField.text = [numtext substringToIndex:10];
}
return YES;
}
网友评论