关于在使用textfield的过程中,经常会遇到限制长度的要求,接下来说一下自己写的oc以及swift的用法:
例如:限制手机号输入框为11位
1.打开textfield的代理,然后在代理方法-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (range.length + range.location > textField.text.length){
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 11;
}
Swift:
//手机号长度判断
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
if (range.length + range.location > textField.text?.characters.count){
return false
}
let newLength:NSInteger = (textField.text?.characters.count)!+string.characters.count-range.length
return newLength<=11
}