Formatting Phone number in Swift

前端 未结 12 1904
天命终不由人
天命终不由人 2020-12-02 09:36

I\'m formatting my textfiled text once the user start typing the phone number into this format type 0 (555) 444 66 77 and it is working fine but once I get the

12条回答
  •  广开言路
    2020-12-02 09:43

    Masked number typing

    /// mask example: `+X (XXX) XXX-XXXX`
    func format(with mask: String, phone: String) -> String {
        let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
        var result = ""
        var index = numbers.startIndex // numbers iterator
    
        // iterate over the mask characters until the iterator of numbers ends
        for ch in mask where index < numbers.endIndex {
            if ch == "X" {
                // mask requires a number in this place, so take the next one
                result.append(numbers[index])
    
                // move numbers iterator to the next index
                index = numbers.index(after: index)
    
            } else {
                result.append(ch) // just append a mask character
            }
        }
        return result
    }
    

    Call the above function from the UITextField delegate method:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return false }
        let newString = (text as NSString).replacingCharacters(in: range, with: string)
        textField.text = format(with: "+X (XXX) XXX-XXXX", phone: newString)
        return false
    }
    

    So, that is work better.

    "" => ""
    "0" => "+0"
    "412" => "+4 (12"
    "12345678901" => "+1 (234) 567-8901"
    "a1_b2-c3=d4 e5&f6|g7h8" => "+1 (234) 567-8"
    

提交回复
热议问题