首字母必须为 0 的 UitextFiled 格式类似于 (0) 1234 56789

UitextFiled with first letter must 0 and format will be like (0) 1234 56789

我正在使用 phone 数字 texfield,现在我正在为 texfield (#) 使用这种格式 #### #####,现在的问题是我想要第一个字符 0 作为强制性的,比如this (0) 1234 56789,所以用户输入第一个字符必须输入0,它的不重复问题编号格式不同

这是我的代码,但它不起作用

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
}

在这种格式中 (#) #### ##### 只使用了两个 space。因此,您可以在特定索引处插入 space 而无需像这样的 for 循环

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 > 14 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    if oldText.count > 3 { 
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 3))
    }
    if oldText.count > 8 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 8))
    }
    textField.text = oldText
    return false
}