UITextView要实现UITextViewDelegate协议:
_descriptionTextView.delegate=self;
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if ([text isEqualToString:@""] && range.length > 0) {
// 删除字符肯定是安全的
return YES;
}
if (textView.text.length - range.length + text.length > 1000) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"超出最大长度" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
return NO;
}
return YES;
}
UITextField要实现UITextFieldDelegate协议:
_exchangeTextField.delegate=self;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.exchangeTextField && textField.isFirstResponder) {
NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([toBeString length] > 8) {
textField.text = [toBeString substringToIndex:8];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"超出最大长度" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
return NO;
}
return YES;
}
return YES;
}