SwiftPhoneNumberFormatter 1.5

SwiftPhoneNumberFormatter 1.5

Sergei ShatunovSerheo Shatunov 维护。



  • Sergei Shatunov

电话号码格式化工具

Build Swift Carthage compatible

UITextField 和 NSFormatter 子类,用于格式化电话号码。允许不同国家使用不同格式(模式)。光标定位效果极佳。Swift 4。
如果您需要 ObjC 支持,请使用 https://github.com/Serheo/SHSPhoneComponent/

安装

Carthage

github "Serheo/PhoneNumberFormatter"

CocoaPods

pod "SwiftPhoneNumberFormatter"

入门

默认格式

textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "(###) ###-##-##")

所有输入字符串都将按这种方式解析。 示例:+1 (123) 123-45-67

Image

前缀格式

您可以在所有输入上设置前缀

textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "(###) ###-##-##")
textField.prefix = "+7 "

多种格式

textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "##########")
textField.prefix = nil
let custom1 = PhoneFormat(phoneFormat: "+# (###) ###-##-##", regexp: "^7[0-689]\\d*$")
textField.config.add(format: custom1)

let custom2 = PhoneFormat(phoneFormat: "+### ###-##-##", regexp: "^380\\d*$")
textField.config.add(format: custom2)

带有前缀的多种格式

textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "### ### ###")
textField.prefix = "+7 "

let custom1 = PhoneFormat(phoneFormat: "(###) ###-##-##", regexp: "^1\\d*$")
textField.config.add(format: custom1)

let custom2 = PhoneFormat(phoneFormat: "(###) ###-###", regexp: "^2\\d*$")
textField.config.add(format: custom2)

监听变化

要通过添加 textDidChangeBlock 闭包来通知 textField 输入变化。

textField.textDidChangeBlock = { field in
  if let text = field?.text, text != "" {
      print(text)
  } else {
      print("No text")
  }

尝试使用其他方式监听变化可能会失败(例如,实现 UITextFieldDelegatetextField:shouldChangeCharactersIn:range:)。

要求

iOS 9+ Swift 4

许可协议

PhoneNumberFormatter 在MIT许可下可用。有关更多信息,请参阅LICENSE文件。