一、需求是输入框输入限制表情的输入,限制输入长度
1、判断是否是九宫格输入
+ (BOOL)isNineKeyBoard:(NSString *)string
{
NSString *other = @"➋➌➍➎➏➐➑➒";
int len = (int)string.length;
for(int i=0;i<len;i++)
{
if(!([other rangeOfString:string].location != NSNotFound))
return NO;
}
return YES;
}
2、判断是否是emoji表情输入
+ (BOOL)stringContainsEmoji:(NSString *)string {
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:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:@""];
return modifiedString.length == 0? YES : NO;
}
3、在textField代理方法里判断
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([FSLMethod isNineKeyBoard:string]) {
return YES;
}
if ([FSLMethod stringContainsEmoji:string]) {
return NO;
}else
return YES;
}
二、输入长度限制
1、给要判断的textField添加监听方法
[nameTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
2、在监听方法里做判断限制
- (void)textFieldEditChanged:(UITextField *)textField
{
[self changeSubBtnBackgroudImage];
if (textField == self.enterpriseTextField) { // 企业全称
[self textFieldEditChanged:textField withMaxLength:30];
}else if (textField == self.nameTextField) { // 名字
[self textFieldEditChanged:textField withMaxLength:10];
}else if (textField == self.positionTextField) { // 职位
[self textFieldEditChanged:textField withMaxLength:10];
}else if (textField == self.addrTextField) { // 详细地址
[self textFieldEditChanged:textField withMaxLength:50];
}
}
- (void)textFieldEditChanged:(UITextField *)textField withMaxLength:(NSInteger)maxlength
{
NSString *toBeString = textField.text;
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > maxlength) {
textField.text = [toBeString substringToIndex:maxlength];
// [self alertInfo:@"商讯标签超出字数限制"];
// self.titleRightLabel.text = @"30/30";
textField.text = [textField.text substringToIndex:maxlength];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else{
if (toBeString.length > maxlength) {
textField.text = [toBeString substringToIndex:maxlength];
// [self alertInfo:@"商讯标签超出字数限制"];
// self.titleRightLabel.text = @"30/30";
textField.text = [textField.text substringToIndex:maxlength];
}
}
}
网友评论