UITextField 输入限制
[_tfTextFeild addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{if (textField == _tfTextFeild){if (string.length == 0) return YES;NSInteger existedLength = textField.text.length;NSInteger selectedLength = range.length;NSInteger replaceLength = string.length;if (existedLength - selectedLength + replaceLength > TEXT_MAXLENGTH){return NO;}}return YES;
}- (void)limitLength:(UITextField *)textField
{if (textField == _tfTextFeild){if (textField.text.length > TEXT_MAXLENGTH){textField.text = [textField.text substringToIndex:TEXT_MAXLENGTH];}}
}
UITextView输入限制
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEditChanged) name:UITextViewTextDidChangeNotification object:nil];
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{if (textView == _contentTextView){if (text.length == 0) return YES;NSInteger existedLength = textView.text.length;NSInteger selectedLength = range.length;NSInteger replaceLength = text.length;if (existedLength - selectedLength + replaceLength > TEXT_MAXLENGTH){return NO;}}return YES;
}- (void)textViewEditChanged
{if (_contentTextView.text.length > TEXT_MAXLENGTH){_contentTextView.text = [_contentTextView.text substringToIndex:TEXT_MAXLENGTH];}
}