我用Google搜索了如何查找国家/地区的列表并尝试实施到PickerView,但是我在这一点上陷入困境,我尝试做country.count它给了我一个错误说:
cannot convert return expression of type ‘int’ to return type ‘string’
any suggestions?
- import UIKit
- class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate{
- @IBOutlet weak var pickerValue: UIPickerView!
- let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in
- let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
- return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier,value: id) ?? "Country not found for code: \(code)"
- }
- func numberOfComponents(in pickerView: UIPickerView) -> Int {
- return 1
- }
- func pickerView(_ pickerView: UIPickerView,titleForRow row: Int,forComponent component: Int) -> String? {
- return countries.count
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view,typically from a nib.
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
您需要在方法numberOfRowsInComponent中返回数组计数,并且在titleForRow中需要返回数组对象,显示它将在picker中显示.
- func pickerView(_ pickerView: UIPickerView,numberOfRowsInComponent component: Int) -> Int {
- return countries.count
- }
- func pickerView(_ pickerView: UIPickerView,forComponent component: Int) -> String? {
- return countries[row]
- }