步骤一:添加textfield协议‘
@interface LsGeXingQianMingVC ()<UITextFieldDelegate>
步骤2:设置代理
_GeXingQianMingTiefield.delegate = self;
步骤3:实现协议
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{ //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
if ([string isEqualToString:@"\n"]) //按会车可以改变
{
return YES;
}
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
if (self.GeXingQianMingTiefield == textField) //判断是否时我们想要限定的那个输入框
{
if ([toBeString length] > 40) { //如果输入框内容大于20则弹出警告
textField.text = [toBeString substringToIndex:20];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
return YES;
}
这样的话就可以进行限制字数了