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

帅比萌擦擦* 提交于 2019-12-13 08:44:59

问题


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
}


来源:https://stackoverflow.com/questions/56360558/uitextfiled-with-first-letter-must-0-and-format-will-be-like-0-1234-56789

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!