【问题标题】:Swift - How to limit the a few specific text field only allow to insert int?Swift - 如何限制几个特定的​​文本字段只允许插入 int?
【发布时间】:2020-08-13 12:23:05
【问题描述】:

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

【问题讨论】:

标签: swift int uitextfield


【解决方案1】:

尝试设置 textField 的键盘类型?

yourTextField.keyboardType = .numberPad

也可以查看委托方法

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

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

【讨论】:

    【解决方案2】:

    试试这个。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多