UitextFiled with first letter must 0 and format wi

2019-09-19 14:59发布

问题:

This question already has an answer here:

  • UiTextfield- First letter must be 0 3 answers

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) 1234 56789, so user enter whatever first character must be typed 0, its not duplicate quesion number format is different

here is my code but its not working

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
}

回答1:

In this format (#) #### ##### only two spaces are used. So you can insert space at a particular index without a for loop like this

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
}