我有一个 UITextField
,我在其中获取月份编号作为输入。我成功地将 UITextField 中的字符数限制为 2。但我希望用户只输入从 1 到 12
的值,而不是其他值。这必须在用户键入数字时同时完成,即在 func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool
中。如果我使用一个简单的 if
条件来检查每个字符并在 else
部分返回 false,文本字段将不允许我使用清除或重新键入任何其他字符。谁来帮帮我。
最佳答案
设置键盘类型为数字键盘
添加这个
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
if let text = textField.text {
let newStr = (text as NSString)
.stringByReplacingCharactersInRange(range, withString: string)
if newStr.isEmpty {
return true
}
let intvalue = Int(newStr)
return (intvalue >= 0 && intvalue <= 12)
}
return true
}
关于ios - 如何在 swift 2.0 的 UITextfield 中只允许特定的一组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34649504/