UiTextfield- First letter must be 0

2020-03-31 07:45发布

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 545, so user enter whatever first character must be typed 0,

this is my code

 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
}

3条回答
甜甜的少女心
2楼-- · 2020-03-31 08:20

If you create Enum, you can choice your textField type and make the extension properties for this field

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
           }
        }
}
查看更多
放我归山
3楼-- · 2020-03-31 08:24

In shouldChangeCharactersIn method of UITextFieldDelegate,

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
}

Append (0) to the newly created string, everytime the textField is edited.

查看更多
迷人小祖宗
4楼-- · 2020-03-31 08:26

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..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}

enter image description here

查看更多
登录 后发表回答