【发布时间】:2020-08-13 12:23:05
【问题描述】:
如何限制少数特定文本字段只允许插入int? 不是所有的文本字段。只有几个具体的。 谢谢。
【问题讨论】:
标签: swift int uitextfield
如何限制少数特定文本字段只允许插入int? 不是所有的文本字段。只有几个具体的。 谢谢。
【问题讨论】:
标签: swift int uitextfield
尝试设置 textField 的键盘类型?
yourTextField.keyboardType = .numberPad
也可以查看委托方法
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
如果 textField 的选择符合您的要求,您可以从那里添加逻辑以返回 true 或 false
【讨论】:
试试这个。
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var yourTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
yourTextField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For mobile numer validation
if textField == yourTextField {
//Add specific int numbers
let allowedCharacters = CharacterSet(charactersIn:"0123 ")//Here change this characters based on your requirement
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
}
【讨论】: