Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

ios - add prefix to uiTextField in swift

I am trying to add country code as prefix to textField so the user can enter the rest of his phone number

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

I got this error Initializer for conditional binding must have Optional type, not 'String'

question from:https://stackoverflow.com/questions/65919711/add-prefix-to-uitextfield-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're force unwrapping MobileLbl.text! which no longer makes it optional. Take off the exclamation point so it's just MobileLbl.text. Also have to move countryCode to another line as it isn't optional either.

let countryCode = "+1"

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

let phoneNumber = countryCode + phone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...