Swift-如何限制一些特定的文本字段只允许插入int



如何限制只允许插入int的少数特定文本字段?并非所有文本字段。只有几个具体的。非常感谢。

试试这个。

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
}
}

是否尝试设置textField的键盘类型?

yourTextField.keyboardType = .numberPad

也可以查看委托方法

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}

如果textField的选择符合您的要求,您可以从那里添加返回true或false的逻辑

最新更新