在 swift 中为 uiTextField 添加前缀

add prefix to uiTextField in swift

我正在尝试将国家代码添加为 textField 的前缀,以便用户可以输入其余的 phone 号码

   @IBAction func phoneLogin(_ sender: Any) {
    let countryCode = "+1"
    
    guard let phoneNumber = countryCode + MobileLbl.text! else { return }
    
    if ((MobileLbl.text?.isEmpty) != nil) {
        print("Fill Your Number")
    }else {
        OTPtxt.isHidden = false
        VerifyBtn.isHidden = false
    PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationId, error) in
        if error == nil {
            guard let verifyId = verificationId else { return }
            self.def.setValue(verifyId, forKey: "verificationId")
            self.def.synchronize()
            
            print(verificationId)
        } else {
            print("Unable to get Secret verification from firebase", error?.localizedDescription)
        }
    }
    
    }
    
}

我收到这个错误 条件绑定的初始化器必须有可选类型,而不是 'String'

您正在强制解包 MobileLbl.text!,这不再使其成为可选的。去掉感叹号,就变成 MobileLbl.text。还必须将 countryCode 移动到另一行,因为它也不是可选的。

let countryCode = "+1"

guard let phone = MobileLbl.text else { return nil }

let phoneNumber = countryCode + phone