我有一个UITextField,我想将字段中允许的最大输入值限制为1000 .eg(1-1000),如果textfield中的值超过1000,则textfield不应该将值设置为输入。我试过以下
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
var newString: String = textField.text.replacingCharacters(in: range, with: string)
var characterSet = CharacterSet(charactersIn: "0123456789,.").inverted
if (newString as NSString).rangeOfCharacter(from: characterSet).location != NSNotFound {
return false
}
return Double(newString) ?? 0.0 < 1000
}
答案 0 :(得分:0)
试试这个。希望这会有所帮助
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1001
}
答案 1 :(得分:0)
尝试从textField中提取整数值,并检查它是否低于1000。
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSInteger inte = [textField.text intValue];
if (inte < 1000 && inte > 0)
return NO;
else
return YES;
}