UiTextfield-首字母必须为0

UiTextfield- First letter must be 0

我正在使用 phone 数字 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
}

UITextFieldDelegateshouldChangeCharactersIn方法中,

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
}

每次编辑 textField 时,将 (0) 附加到新创建的 string

shouldChangeCharactersIn 方法中 return 如果新字符串计数大于 15,则为 false。否则删除 (0) 并清空 spaces,然后如果字符串不是空在开头添加(0)。然后将字符串按每 3 个字符拆分,并使用 space 分隔符连接所有字符串。

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: [=10=])
        let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
        return String(oldText[sIndex..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}

如果您创建 Enum,您可以选择您的 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
           }
        }
}