问题描述
我需要在 UITextField 中将电话号码格式显示为占位符.我该怎么办?
I need to display phone number format as placeholder in UITextField. How can I do that?
对于国家/地区选择,我使用下面提到的库,它提供了针对用户选择的国家/地区的国家标记和国家/地区代码.
For country selection I'm using below mentioned library and it provides me country flag and country code against user selected country.
https://github.com/NikKovIos/NKVPhonePicker
选择一个国家/地区后,我需要显示该所选国家/地区的电话号码格式,并且在提交该电话号码后,我必须验证电话号码.
After selecting a country I need to display phone number format for that selected country and on submission of that phone number I have to validate the phone number.
我还发现,第三方( PhoneNumberKit )受到Google的libphonenumber的启发,但用于验证,它没有针对国家/地区代码提供预期的电话号码格式.下面是链接.
I also find that third party (PhoneNumberKit) which is inspired by google's libphonenumber but it is for validating, it do not provide expected phone number format against country code. Below is the link.
https://github.com/marmelroy/PhoneNumberKit
更新1:尝试过此操作并得到通用解析器错误
Update 1:Tried this and getting Generic parser error
let phoneNumberKit = PhoneNumberKit()
do {
let phoneNumber = try phoneNumberKit.parse("+921230123456")
}
catch {
print("Generic parser error")
}
更新2:更新了代码,仍然出现异常
Update 2:Updated code, still getting 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")
}
推荐答案
对于那些想做同样事情的人,我使用了两个不同的第三方来实现该功能.
For those who wanna do the same thing, I used two different 3rd parties to achieve the functionality.
- NKVPhoneNumber
- SHSPhoneComponent
NKVPhoneNumber 用于选择国家/地区代码,我在元数据中对引入的phone_format
进行了一些修改.从列表中选择一个国家后,它会返回一个包含Code, Extension, Flag and format_placeholder
NKVPhoneNumber is used to select country code, i've modified it a bit a introduced phone_format
in the Meta Data. Once selected a country from the list it return a Country
object which includes Code, Extension, Flag and format_placeholder
SHSPhoneComponent ,然后使用该format_placeholder
进行格式验证.
SHSPhoneComponent then use that format_placeholder
for validation of the format.
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 ,
这篇关于iOS上国家/地区代码中的电话号码格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!