0

How to make picker view to display from default country but it is displaying from first but I need it from default country that is united states but here it is showing from first country but I need it to display from United States can anyone help me how to implement this ?

here are the images shown below here picker view displaying from first country but I need it to display from United States because it is my default selected country

enter image description hereenter 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")
        }
    }
  • Possible duplicate of [Swift: How to set a default Value of a UIPickerView with three components in Swift?](https://stackoverflow.com/questions/25917693/swift-how-to-set-a-default-value-of-a-uipickerview-with-three-components-in-swi) and https://stackoverflow.com/questions/11777072/how-to-set-a-default-value-of-a-uipickerview – Sandeep Bhandari Dec 06 '17 at 06:16
  • but it's still opening picker view from first country itself @SandeepBhandari –  Dec 06 '17 at 06:45
  • May I know what did you modify in your code from the reference I provided for duplicate. Please update your question with what you tried from the reference posted above. If there is still issue we will be happy to help you. I can post the answer but there is no benefit to community with duplicate answers hence refraining doing so – Sandeep Bhandari Dec 06 '17 at 07:01
  • I had added this code in view did load `countryPickerView.selectRow(37, inComponent: 0, animated: true)` and when I click on country text field country picker view has opened but the first country shown here is `Afghanistan` but not `United States` I need it to be `United States` but not `Afghanistan` –  Dec 06 '17 at 07:21
  • Adding code in viewDidLoad will not work because by then your countryPickerView does not have a the data yet :) Think a little more and you have your answer :D – Sandeep Bhandari Dec 06 '17 at 07:37
  • after parsing countries there also i included the code as `countryPickerView.selectRow(37, inComponent: 0, animated: true)` but didn't work seriously not getting bro I had posted my modified code –  Dec 06 '17 at 07:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160575/discussion-between-sandeep-bhandari-and-user). – Sandeep Bhandari Dec 06 '17 at 08:23

3 Answers3

1

Have class variables to track selection. It should be updated by your picker delegate function func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int). Instead of updating in viewDidLoad() you will have to update the selection in func viewWillAppear(_ animated: Bool) for the values to be updated each time. viewDidLoad() is executed only the first time the view is loaded, not every time it is visited.

In swift 4, it would look like this :

//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))
    }
Rathna
  • 21
  • 3
0

you can use ActionSheetPicker which in fact reduces the code of all picker methods & you can get your selected country as default in picker view using else condition

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();
    }

Here self.selectedCountry = selectedIndex helps you to manage selectedCountry Index dynamically

  • @User let me know if this answer was helpful to you or not –  Dec 06 '17 at 07:20
  • no I just need to do it with normal picker view not to go for another libraries any how thanks for reply @D.Desai –  Dec 06 '17 at 07:26
0

First thing you need to know what is the index of United States. So store it's index in variable selectedCountry when you are calling the api. After that call the pickers delegate method 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()
    }

Hope this will be help.

Zealous System
  • 2,080
  • 11
  • 22
  • Already I am giving statically in view did load code i.e. like this `countryPickerView.selectRow(37, inComponent: 0, animated: true)` but picker view was loading from first country itself not from passed value –  Dec 06 '17 at 07:25
  • 1
    after getting the response first you need to call self.countryPickerView.reloadAllComponents and after that set the countryPickerView.selectRow(37, inComponent: 0, animated: true) – Zealous System Dec 06 '17 at 08:30