引言需求:(輸入框限制輸入多少字符)
1、一個字母、符號、數字相當於一個字符
2、一個漢字相當於兩個字符
3、不能輸入特殊字符
4、不能輸入emoji表情
直接上代碼
一、注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextViewTextDidChangeNotification object:nil];
二、通知實現
- (void)textFieldChange:(UITextField *)textField { //判斷輸入(不能輸入特殊字符) [RestrictionInput restrictionInputTextField:self.titleTextField maxNumber:100 showView:self showErrorMessage:@"商品名稱0~100字符~"]; [RestrictionInput restrictionInputTextView:self.infoTextView maxNumber:200 showView:self showErrorMessage:@"商品描述0~200字符~"]; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([RestrictionInput isInputRuleAndBlank:text] || [text isEqualToString:@""]) {//當輸入符合規則和退格鍵時允許改變輸入框 return YES; } else { return NO; } } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([RestrictionInput isInputRuleAndBlank:string] || [string isEqualToString:@""]) {//當輸入符合規則和退格鍵時允許改變輸入框 return YES; } else { return NO; } }
三、封裝類(RestrictionInput)
.h
#import <Foundation/Foundation.h> @interface RestrictionInput : NSObject + (void)restrictionInputTextField:(UITextField *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage; + (void)restrictionInputTextView:(UITextView *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage; + (BOOL)isInputRuleAndBlank:(NSString *)str;
.m
#import "RestrictionInput.h" @implementation RestrictionInput + (void)restrictionInputTextField:(UITextField *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage { NSString *toBeString = inputClass.text; if (![self isInputRuleAndBlank:toBeString]) { inputClass.text = [self disable_emoji:toBeString]; return; } NSString *lang = [[inputClass textInputMode] primaryLanguage]; // 獲取當前鍵盤輸入模式 if([lang isEqualToString:@"zh-Hans"]) { //簡體中文輸入,第三方輸入法(搜狗)所有模式下都會顯示“zh-Hans” UITextRange *selectedRange = [inputClass markedTextRange]; //獲取高亮部分 UITextPosition *position = [inputClass positionFromPosition:selectedRange.start offset:0]; //沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制 if(!position) { NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber]; if(getStr && getStr.length > 0) { inputClass.text = getStr; [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil]; NSLog(@"%@", inputClass.text); } } } else{ NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber]; if(getStr && getStr.length > 0) { inputClass.text= getStr; [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil]; NSLog(@"%@",inputClass.text); } } } + (void)restrictionInputTextView:(UITextView *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage { NSString *toBeString = inputClass.text; if (![self isInputRuleAndBlank:toBeString]) { inputClass.text = [self disable_emoji:toBeString]; return; } NSString *lang = [[inputClass textInputMode] primaryLanguage]; // 獲取當前鍵盤輸入模式 if([lang isEqualToString:@"zh-Hans"]) { //簡體中文輸入,第三方輸入法(搜狗)所有模式下都會顯示“zh-Hans” UITextRange *selectedRange = [inputClass markedTextRange]; //獲取高亮部分 UITextPosition *position = [inputClass positionFromPosition:selectedRange.start offset:0]; //沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制 if(!position) { NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber]; if(getStr && getStr.length > 0) { inputClass.text = getStr; [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil]; NSLog(@"%@", inputClass.text); } } } else{ NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber]; if(getStr && getStr.length > 0) { inputClass.text= getStr; [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil]; NSLog(@"%@",inputClass.text); } } } /** * 獲得 kMaxLength長度的字符 */ + (NSString *)getSubString:(NSString*)string maxNumber:(NSInteger)maxNumber { NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSData* data = [string dataUsingEncoding:encoding]; NSInteger length = [data length]; if (length > maxNumber) { NSData *data1 = [data subdataWithRange:NSMakeRange(0, maxNumber)]; NSString *content = [[NSString alloc] initWithData:data1 encoding:encoding];//【注意4】:當截取kMaxLength長度字符時把中文字符截斷返回的content會是nil if (!content || content.length == 0) { data1 = [data subdataWithRange:NSMakeRange(0, maxNumber - 1)]; content = [[NSString alloc] initWithData:data1 encoding:encoding]; } return content; } return nil; } /** * 字母、數字、中文正則判斷(不包括空格) */ + (BOOL)isInputRuleNotBlank:(NSString *)str { NSString *pattern = @"^[➋➌➍➎➏➐➑➒\a-zA-Z\u4E00-\u9FA5\\d]*$"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; BOOL isMatch = [pred evaluateWithObject:str]; return isMatch; } /** * 字母、數字、中文正則判斷(包括空格)【注意3】 */ + (BOOL)isInputRuleAndBlank:(NSString *)str { //九宮格無法輸入解決需要加上正則 \➋➌➍➎➏➐➑➒ NSString *pattern = @"^[➋➌➍➎➏➐➑➒\a-zA-Z\u4E00-\u9FA5\\d\\s]*$"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; BOOL isMatch = [pred evaluateWithObject:str]; return isMatch; } + (NSString *)disable_emoji:(NSString *)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; }
以上所述是小編給大家介紹的iOS UITextField、UITextView只限輸入中文、英文、數字及實時限制字符個數封裝實現,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對本站網站的支持!