如何使选择器视图从swift 3中的特定行显示?

时间:2017-12-06 06:13:50

标签: ios swift3 uipickerview

如何让选择器视图显示在默认国家/地区,但它从一开始就显示但我需要来自united states的默认国家/地区,但此处显示的是第一个国家/地区,但我需要它来自美国任何人都可以帮我解决这个问题吗?

以下是此处显示的图片,此处显示从第一个国家/地区的选择器视图,但我需要它从美国显示,因为它是我默认选择的国家/地区

enter image description here enter image description here

func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for item in jsonObj! {
                    let dict = Country(dict: item)
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                     self.countryPickerView.selectRow(self.i, inComponent: 0, animated: true)
                     self.countryPickerView.reloadAllComponents()
                     self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }  


    func numberOfComponents(in pickerView: UIPickerView) -> Int{
        if pickerView.tag == 1 {
            return 1
        }else {
            return 1
        }
    }


    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView.tag == 1 {
            return countryArray.count
        }
        else {
            return countryArray[countrySelectedIndex!].state.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 1 {
            return countryArray[row].country
        }
        else {
            return countryArray[countrySelectedIndex!].state[row].state
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView.tag == 1 {
            countryTextField.text = countryArray[row].country
            for item in countryArray {
                print(item.country)
                print(countryArray[row].country)
                if item.country == countryArray[row].country {
                    self.countryId = item.countryId
                    if item.state.count == 0 {
                        self.stateTextfield.isHidden = false
                        self.stateLabel.isHidden = true
                        self.selectedCountryTextField.isHidden = true
                        self.imageArrow.isHidden = true
                        break
                    }
                    else {
                        if let i = countryArray.index(where: { $0.country == countryArray[row].country }) {
                            countrySelectedIndex = i
                        }
                        self.countryId = item.countryId
                        if self.countryId?.isEmpty == true {
                            self.countryId = countryTextField.text
                        }
                        UserDefaults.standard.set(self.countryId, forKey: "guestCountryId")
                        self.statePickerView.delegate = self
                        self.statePickerView.dataSource = self
                        selectedCountryTextField.inputView = statePickerView
                        self.statePickerView.reloadAllComponents()
                        selectedCountryTextField.text = "Select state/province"
                        self.stateLabel.isHidden = false
                        self.stateTextfield.isHidden = true
                        self.selectedCountryTextField.isHidden = false
                        self.imageArrow.isHidden = false
                        break
                    }
                }
                else {
                    self.stateTextfield.isHidden = false
                    self.stateLabel.isHidden = true
                    self.selectedCountryTextField.isHidden = true
                    self.imageArrow.isHidden = true
                }
            }
        }
        else {
            self.selectedCountryTextField.text = countryArray[countrySelectedIndex!].state[row].state
            self.stateCode = countryArray[countrySelectedIndex!].state[row].stateValue as! Int
            print(self.stateCode)
            UserDefaults.standard.set(self.stateCode, forKey: "statecode")
        }
    }

3 个答案:

答案 0 :(得分:1)

有类变量来跟踪选择。它应该由您的选择器委托函数func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)更新。您不必在viewDidLoad()中更新,而是必须更新func viewWillAppear(_ animated: Bool)中的选择,以便每次更新值。 viewDidLoad()仅在第一次加载视图时执行,而不是每次访问时都执行。

在swift 4中,它看起来像这样:

//class variable
var selectedCountry:Int = 0
var column : Int = 0

    // Catpure the picker view selection
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            selectedCountry = row
            column = component 
    }

    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated);
            countryPickerView.selectRow(selectedCountry, inComponent: column, animated: true))
    }

答案 1 :(得分:0)

你可以使用ActionSheetPicker,这实际上减少了所有选择器方法的代码。您可以使用其他条件

将所选国家/地区设置为选择器视图中的默认国家/地区
if txtCountry.text == ""
    {
        let countryPicker = ActionSheetStringPicker(title: "Select a country", rows: pickerData, initialSelection: 0, doneBlock: { (pickerSheet, selectedIndex, selectedValue) in    
            self.txtCountry.text = selectedValue! as? String
            self.selectedCountry = selectedIndex
        }, cancel: {pickerSheet in return }, origin: (sender as AnyObject).superview!)
        countryPicker?.show();
    }
    else
    {
        let countryPicker = ActionSheetStringPicker(title: "Select a country", rows: pickerData, initialSelection: selectedCountry, doneBlock: { (pickerSheet, selectedIndex, selectedValue) in
            self.txtCountry.text = selectedValue! as? String
            self.selectedCountry = selectedIndex

        }, cancel: {pickerSheet in return }, origin: (sender as AnyObject).superview!)
        countryPicker?.show();
    }

此处self.selectedCountry = selectedIndex可帮助您动态管理selectedCountry索引

答案 2 :(得分:0)

首先你需要知道美国的指数是什么。因此,当您调用api时,将它的索引存储在变量selectedCountry中。之后调用选择器委托方法selectedRow。

var selectedCountry:Int = 0

func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for itemNumber in 0..<jsonObj!.count {
                    let dict = Country(dict:jsonObj![itemNumber])
                    if dict.countryName == "United States" {
                        self.selectedCountry = itemNumber
                        self.countryPickerView.selectRow(self.selectedCountry, inComponent: 0, animated: true)
                    }
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                    self.countryPickerView.reloadAllComponents()
                    self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }

希望这会有所帮助。