在 swift 中防止 phone 填充文本字段上的第一个字符为“0”

Prevent "0" first character on phone pad textfield in swift

如何防止第一个字符输入“0”,例如,如果 phone 数字以 012345678 开头,那么它应该首先防止输入“0”。下面是swift代码

class LoginVC: UIViewController {   
var isShowFilter = false
    @IBOutlet weak var txtPhone: UITextField!
    @IBOutlet weak var txtPassword: UITextField!
    @IBOutlet weak var btnLogin: ThemeButton!
    func validateView() -> Bool{
       if (self.txtPhone.text?.isEmpty)!{
            GFunctions.ShowAlert(message: StringIdentifier.EnterPhone.rawValue)
            return false
        }
       else if ((self.txtPhone.text?.starts(with: "0")) != nil){
        GFunctions.ShowAlert(message: StringIdentifier.NoEnterZero.rawValue) //Here want to show toast message if user put 0 at first
        return false
       }
       else if (self.txtPassword.text?.isEmpty)!{
            GFunctions.ShowAlert(message: StringIdentifier.EnterPassword.rawValue)
            return false
       }else if (self.txtPassword.text?.count)! < 6 {
            GFunctions.ShowAlert(message: StringIdentifier.ValidPassword.rawValue)
            return false
        }else{
            return true
        }
    }   
    @IBAction func btnLoginTapped(_ sender: UIButton) {
        if validateView(){
            isShowFilter = true
            self.APICallLogin()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
}

enum StringIdentifier : String{
case NoEnterZero                   = "Do not start with 0"
}

只需实现 TextField 委托

extension LoginVC: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if range.location == 0 && string == "0" {
            return false
        }
        return true
    }
}

确保将 YourViewController 设置为 TextField 委托

override func viewDidLoad() {
     super.viewDidLoad()
     txtPhone.delegate = self
}