How to restrict UITextField to take only numbers in Swift?

后端 未结 30 899
难免孤独
难免孤独 2020-12-04 08:40

I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

30条回答
  •  伪装坚强ぢ
    2020-12-04 08:58

    In swift 4.1 and Xcode 9.4.1

    Add UITextFieldDelegate to your class

    class YourViewController: UIViewController, UITextFieldDelegate
    

    Then write this code in your viewDidLoad()

    mobileNoTF.delegate = self
    

    Write this textfield delegate function

    //MARK - UITextField Delegates
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //For mobile numer validation
        if textField == mobileNoTF {
            let allowedCharacters = CharacterSet(charactersIn:"+0123456789 ")//Here change this characters based on your requirement
            let characterSet = CharacterSet(charactersIn: string)
            return allowedCharacters.isSuperset(of: characterSet)
        }
        return true
    }
    

提交回复
热议问题