实现的方法其实有很多,有好,有坏。最好的是方法二,方法一和三是自己在实现该功能时摸索着写的。
另外,UITextView也有相似的代理方法
添加UITextFieldDelegate,将textField的delegate赋给self,即:
textfield.delegate = self;
- 方法一
#pragma mark - uitextfield 的代理方法
//判断 支付密码的字数是否大于8 位 ,小于20,比较low的方法,在输入结束时判断
- (void)textFieldDidEndEditing:(UITextField *)textField{
if (textField.tag == 2) { //判断是tag=2的textfield的内容长度
if (textField.text.length < 8) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"新支付密码的长度至少为8位" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show]; //给出提示
textField.text = @"” ; //将内容置空,变相清除textfield的内容
} else if(textField.text.length >20) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"新支付密码的长度不能超过20位" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
textField.text = @"" ;
}
}
}
- 方法二
到达限制长度后,无论用户再怎么输入,只显示限制长度内的字符
#pragma mark -- 实时监控字符的代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location >=8)
return NO; // 返回no,则textfield文本不在改变
return YES; //textfield文本还可以变化,即可以再输入
}
- 方法三
同方法二一样,到达限制长度后,无论用户再怎么输入,只显示限制长度内的字符
#pragma mark - 字数限制
- (void)textViewDidChange:(UITextView *)textView{
if ([textView.text length] > 100)
{
textView.text = [textView.text substringToIndex:100];
if (!_isAlert) {
_isAlert = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"个性签名字数不超过100。" delegate:self
cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
}
}