Swift - 如何限制几个特定的​​文本字段只允许插入int?

Swift - How to limit the a few specific text field only allow to insert int?

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

试过设置文本字段的键盘类型吗?

yourTextField.keyboardType = .numberPad

也可以看看委托方法

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

如果文本字段的选择符合您的要求,您可以从那里添加逻辑 return 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
        }

    }