国家代码中的电话号码格式

我需要在UITextField中将电话号码格式显示为占位符。 请让我知道我该怎么做。

对于国家选择我使用下面提到的图书馆,它提供了国家标志和国家代码与用户选择的国家。

https://github.com/NikKovIos/NKVPhonePicker

选择国家/地区后,我需要显示所选国家/地区的电话号码格式,并且在提交该电话号码后,我必须validation电话号码。

我还发现第三方( PhoneNumberKit )的灵感来自google的libphonenumber,但它用于validation,它不提供针对国家/地区代码的预期电话号码格式。 以下是链接。

https://github.com/marmelroy/PhoneNumberKit

谢谢

更新1:试过这个并获得通用解析器错误

let phoneNumberKit = PhoneNumberKit() do { let phoneNumber = try phoneNumberKit.parse("+921230123456") } catch { print("Generic parser error") } 

更新2:更新了代码,仍然出现exception

 let phoneNumberKit = PhoneNumberKit() do { let phoneNumber = try phoneNumberKit.parse("1230123456", withRegion: "FR", ignoreType: false) let formatedNumber = phoneNumberKit.format(phoneNumber, toType: .international) print(formatedNumber) } catch { print("Generic parser error") } 

我不知道这是否是一个有效的解决方案,你可以试试这个

说让你的占位符为012345679我相信你能做的就是

  • 创建一个变量来存储此占位符
  • 根据用户选择的国家/地区解析此占位符。
  • 将已解析的一个设置为文本字段中的占位符。

对于那些想做同样事情的人,我使用了两个不同的第三方来实现这个function。

  1. NKVPhoneNumber
  2. SHSPhoneComponent

NKVPhoneNumber用于选择国家代码,我在元数据中修改了一下介绍的phone_format 。 从列表中选择一个国家后,它将返回一个Country对象,其中包括Code, Extension, Flag and format_placeholder

然后, format_placeholder使用该format_placeholder来validation格式。

 import SHSPhoneComponent import NKVPhonePicker @IBOutlet weak var phoneTF: SHSPhoneTextField! @IBOutlet weak var phoneFlag: NKVPhonePickerTextField! @IBOutlet weak var lblCountryCode: UILabel! //MARK: - NKV callback delegates func countriesViewController(_ sender: CountriesViewController, didSelectCountry country: Country) { // phoneTF.formatter.setDefaultOutputPattern(country.formatPattern) phoneTF.text = "" phoneTF.placeholder = country.formatPatternPlaceHolder countryCode = "+\(country.phoneExtension)" lblCountryCode.text = countryCode } 

注意:我已将NVKPhoneNumber转换为Swift 4.0