UITextView和UITextField限制输入长度
程序员文章站
2022-04-06 08:08:36
...
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;
}
推荐阅读
-
IOS 中UITextField和UITextView中字符串为空和空格的解决办法
-
IOS中UITextView或UITextField字数限制的实现
-
IOS 中UITextField和UITextView中字符串为空和空格的解决办法
-
使用UITextField限制只可输入中,英文,数字的方法
-
WPF TextBox实现按字节长度限制输入功能
-
IOS中UITextView或UITextField字数限制的实现
-
仅几行iOS代码限制TextField输入长度
-
TextField和TextView限制输入字数长度
-
iOS输入框的字数统计/最大长度限制详解
-
使用UITextField限制只可输入中,英文,数字的方法