UiTextfield- First letter must be 0

后端 未结 3 967
名媛妹妹
名媛妹妹 2021-01-17 04:03

I am using phone number texfield, now i am using this format for texfield (#) ### ### ###, now issue is that i want first character 0 as compulsary, like this (0) 959 554 54

3条回答
  •  鱼传尺愫
    2021-01-17 05:07

    In shouldChangeCharactersIn method of UITextFieldDelegate,

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let text = textField.text {
            let str = (text as NSString).replacingCharacters(in: range, with: string).replacingOccurrences(of: "(0)", with: "")
            if !str.isEmpty {
                textField.text = "(0)" + str
            } else {
                textField.text = nil
            }
        }
        return false
    }
    

    Append (0) to the newly created string, everytime the textField is edited.

提交回复
热议问题