项目要求限制文本输入长度,内容等。。。。
先说tf 在代理中实现 如用户名是手机号 要求最多只能输入11位
-
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@""]) {//如果是删除键当然可以无所谓了
return YES;
}else if (self.phoneTF.text.length >= 11) {
self.phoneTF.text = [textField.text substringToIndex:11];
return NO;
}return YES;
}
//这个是限制只能再小数点后输入两位数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@""]) {
return YES;
}
static NSInteger strLoc;
if ([string isEqualToString:@"."]) {
strLoc = range.location;
}
if (strLoc != 0 && (range.location - strLoc) > 2 && range.location > strLoc) {//这里要注意下,如果是一个页面中有多个tf要实现代理,必须加上range.location > strLoc,不然肯定会走下去的
textField.text = [textField.text substringToIndex:(strLoc + 3)];
[[[UIAlertView alloc]initWithTitle:@"提示" message:@"小数点后只能输入两位数字" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil]show];
return NO;
}
NSLog(@"location---%lu",(unsigned long)range.location);
NSLog(@"length---%lu",(unsigned long)range.length);
return YES;
}
还有一种是类似微博评论的 右下角会显示 1/200 这样字数限制的 如果是在
-
(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
方法中添加在超出时显示不正确,应该在改变后的方法中 -
(void)textViewDidChange:(UITextView *)textView{
if (textView.text.length >= 200) {
_tv.text = [textView.text substringToIndex:200];
_textNum.text = @"200/200";
}else{
_textNum.text = [NSString stringWithFormat:@"%zd/200",textView.text.length];
}
}
为了这些 真是把两个代理的每个方法都试了一遍,记录下 省的忘了再耽误时间
网友评论