UiTextfield-首字母必须为0

时间:2019-05-20 06:58:32

标签: ios swift uitextfield

我正在使用电话号码texfield,现在我在texfield中使用这种格式(#)### ### ###,现在的问题是我希望将第一个字符0强制性化,例如(0)959 554 545,因此用户输入的任何第一个字符都必须输入0,

这是我的代码

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newString = textField.text
    if ((newString == "") && (newString?.count == 0)){
        txtMobileNumber.text = "0"
        return true
    }else if ((newString?.count)! > 0){
        return true
    }
    return false
}

3 个答案:

答案 0 :(得分:2)

shouldChangeCharactersIn的{​​{1}}方法中,

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 } 时,将(0)附加到新创建的string

答案 1 :(得分:1)

shouldChangeCharactersIn方法中,如果新字符串数大于15,则返回false。否则,请删除(0)并保留空格,然后,如果字符串不为空,请在开头添加(0)。然后将字符串每3个字符分割一次,并用空格分隔符将所有字符串连接起来。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 15 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    let newText = String(stride(from: 0, to: oldText.count, by: 3).map {
        let sIndex = String.Index(encodedOffset: $0)
        let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
        return String(oldText[sIndex..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}

enter image description here

答案 2 :(得分:1)

如果创建枚举,则可以选择textField类型并为此字段设置扩展名属性

func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if cellType == .phone {
            guard var sanitizedText = textField.text else { return true }
           if !sanitizedText.isEmpty && !sanitizedText.hasPrefix("(0)") {
              sanitizedText.text = "(0)" + sanitizedText
           }
        }
}