##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