TextFieldPhoneNumberFormatter

public final class TextFieldPhoneNumberFormatter

TextFieldPhoneNumberFormatter is a helper to perform As-You-Type-Formatting on a UITextField. The formatter performs formatting based on the region country code given at initialization.

Example usage:

let textField = TextField.init(...);
let isoCountryCode = DeviceRegion.currentCountryCode();

let formatter = TextFieldPhoneNumberFormatter(countryCode: isoCountryCode);
formatter.textField = textField;
textField.placeholder = formatter.exampleNumber(format:PhoneNumberFormat.National);

formatter.onTextFieldTextDidChange = { (textField: UITextField) -> Void in
    let text = textField.text != nil ? textField.text! : "";
    let util = SharedPhoneNumberUtil();
    let isPossible = util.isPossibleNumber(textField.text, 
                                           fromRegion: isoCountryCode);

    // Update GUI to hint whether current 
    // user input is a viable phone number.
}
  • Default initialization. Equivalent to initializing with SharedPhoneNumberUtil() and DeviceRegion.currentCountryCode().

    Declaration

    Swift

    public init()
  • Initialize with a specific country code.

    Declaration

    Swift

    public init(countryCode: String)

    Parameters

    countryCode ISO 3166

    -1 two-letter country code that indicates the country/region where the phone number is being entered.

  • onTextFieldTextDidChange is a callback that is invoked when the text value of the observed UITextField changes. This callback handles both events from UITextFieldTextDidChangeNotification and KVO-events for the UITextField.text property.

    It can be used to implement additional hooks like indicating to the user whether the current input is a possibly valid phone number, e.g. with PhoneNumberUtil.isPossibleNumber.

    Declaration

    Swift

    public var onTextFieldTextDidChange: ((UITextField) -> Void)?
  • Get a an example phone number formatted according to given format.

    The returned string can be used as placeholder text for a UITextField.

    Declaration

    Swift

    public func exampleNumber(_ format:PhoneNumberFormat) -> String?

    Return Value

    a formatted phone number string. Will return an empty string if no example phone number is available for the given region country code.