UiTextfield- First letter must be 0

后端 未结 3 1003
名媛妹妹
名媛妹妹 2021-01-17 04:03

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) 959 554 54

3条回答
  •  感动是毒
    2021-01-17 04:55

    In shouldChangeCharactersIn method return false if new string count is greater than 15. Else remove (0) and empty spaces, then if the string isn't empty add (0) at the beginning. Then split the string by every 3 characters and join all string with space separator.

    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..

提交回复
热议问题