Swift 4实现iOS原生国家选择器:国家代码转名称问题咨询
解决Swift 4中ISO国家代码转国家名称的问题
嘿,这个问题我刚好处理过!在Swift 4里把ISO国家代码转成对应的国家名称其实很简单,用系统的Locale(或者兼容的NSLocale)就能轻松搞定,下面给你一步步讲怎么实现:
1. 先把代码转成带名称的数组
首先,你可以创建一个结构体来存储国家代码和对应的名称,这样后续在TableView里使用会更清晰:
struct Country { let code: String let name: String } // 全局或者ViewController里的变量 var countries: [Country] = []
然后在viewDidLoad里初始化这个数组,把NSLocale.isoCountryCodes里的每个代码转成名称,还可以顺便按名称排序,让列表更友好:
override func viewDidLoad() { super.viewDidLoad() let countryCodes = NSLocale.isoCountryCodes as [String] // 使用当前系统语言的名称 countries = countryCodes.compactMap { code in guard let countryName = Locale.current.localizedString(forRegionCode: code) else { return nil } return Country(code: code, name: countryName) }.sorted { $0.name < $1.name } // 按国家名称字母排序 }
如果你想要固定显示英文名称(不管系统语言设置),可以把Locale.current换成固定的英文Locale:
let englishLocale = Locale(identifier: "en_US_POSIX") countries = countryCodes.compactMap { code in guard let countryName = englishLocale.localizedString(forRegionCode: code) else { return nil } return Country(code: code, name: countryName) }.sorted { $0.name < $1.name }
2. 在TableView数据源里使用
现在你的数据源数组countries已经包含了所有国家的名称和代码,直接在TableView的数据源方法里调用就行:
// 返回行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return countries.count } // 配置Cell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CountryCell", for: indexPath) let currentCountry = countries[indexPath.row] cell.textLabel?.text = currentCountry.name // 显示国家名称 cell.detailTextLabel?.text = currentCountry.code // 可选:显示国家代码 return cell }
这样你的国家选择器就能正常显示每个国家的名称了,而且点击后还能通过currentCountry.code拿到对应的ISO代码,完美适配你之前的代理逻辑~
内容的提问来源于stack exchange,提问作者clementb49
相关产品推荐
相关产品推荐

