How can I declare that a text field can only contain an integer?

前端 未结 9 1908
星月不相逢
星月不相逢 2020-11-30 05:37

In swift, I am trying to make a text field that will allow a button to be enabled, but only when the text field contains an integer. How can I do this?

9条回答
  •  盖世英雄少女心
    2020-11-30 06:35

    1st you have to inherit the UITextViewDelegate class with you own class

    class ViewController: UIViewController, UITextViewDelegate {
    

    2nd add an IBOutlet

    @IBOutlet weak var firstName: UITextField!
    

    3rd you have to assure this object is using

    override func viewDidLoad() {
            super.viewDidLoad()
       firstName.delegate = self
    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == firstName {
                    let allowedCharacters = "1234567890"
                    let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                    let typedCharacterSet = CharacterSet(charactersIn: string)
                    let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
                  return alphabet
    
    
    
          }
      }
    

提交回复
热议问题