简单说明:
UITextField限制限制字符串长度:例如要求字符串长度为11位,则textField.text.length > 10
代码如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.userName) {
if (textField.text.length > 10 && string.length > 0) return NO;
}
return YES;
}
Swift
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let proposeLength = (textField.text?.lengthOfBytes(using: String.Encoding.utf8))! - range.length + string.lengthOfBytes(using: String.Encoding.utf8)
if proposeLength > 20 { return false }
return true
}
UITextField限制限制字符串对应的int数值:例如要求字符串>100
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (string.length == 0)
{
}
else
{
if ([textField.text integerValue] * 10 + [string integerValue]>100)
{
return NO;
}
}
return YES;
}
网友评论