##textField的代理方法session
@protocol UITextFieldDelegate <NSObject> @optional - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing. - (void)textFieldDidBeginEditing:(UITextField *)textField; // became first responder - (BOOL)textFieldShouldEndEditing:(UITextField *)textField; // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end - (void)textFieldDidEndEditing:(UITextField *)textField; // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called - (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0); // if implemented, called in place of textFieldDidEndEditing: - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text - (BOOL)textFieldShouldClear:(UITextField *)textField; // called when clear button pressed. return NO to ignore (no notifications) - (BOOL)textFieldShouldReturn:(UITextField *)textField; // called when 'return' key pressed. return NO to ignore.
首先你能够利用代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
这个方法来限制。举个例子。我须要限定50长度的字符。code
NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (toBeString.length > INPUTMAXLENTH && range.length != 1 ) { textField.text = [toBeString substringToIndex:INPUTMAXLENTH]; [[TipView sharedInstance] showMessage:@"最多输入50个字"]; return NO; } return YES;
当你返回YES 才会成功。返回NO 就不会显示。server
##textField的通知 可是你发现 若是点智能添加的话。这样 就会限制不住了。因此还须要有一个方法。ip
UIKIT_EXTERN NSNotificationName const UITextFieldTextDidBeginEditingNotification; UIKIT_EXTERN NSNotificationName const UITextFieldTextDidEndEditingNotification; UIKIT_EXTERN NSNotificationName const UITextFieldTextDidChangeNotification;
他还有三个通知。 调用利用didChangeNotification通知来限制字符。ci
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChange:) name:@"UITextFieldTextDidChangeNotification" object:self.orderTimeText]; 而后调用方法把你的textfield传过来 - (void)textFieldEditChange:(NSNotification *)notify{ UITextField *textField = notify.object; NSString * toBeString = textField.text; if (toBeString.length > INPUTMAXLENTH) { [[TipView sharedInstance] showMessage:@"最多输入50个字"]; textField.text = [toBeString substringToIndex:INPUTMAXLENTH]; }else{ textField.text = toBeString; } }
这样的话 就会限制住了。~~~ 可是提醒一下 使用通知后 不要忘记移除哦。rem