Search code examples
iosarraysswiftuipickerview

How to reload, and reset the number of rows in a UIPickerView - Swift


I have a custom picker view, that I need to occupy with elements from an array that I retrieve from parse. However, because the number of elements in the picker are defined before the array is retrieved from parse, the picker wheel displays as empty. How can I reload the contents, and the number of rows in the picker view? Here is my code:

var dates = [String]() 
var locations = [String]() 

@IBOutlet weak var myPicker: UIPickerView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    var query = PFUser.query()
    query.getObjectInBackgroundWithId(PFUser.currentUser().objectId) { (object: PFObject!, error: NSError!) -> Void in
        self.dates = object["userLocationsDate"] as [String]
        self.locations = object["userLocationsCity"] as [String]
    }

   myPicker.reloadAllComponents()

}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    return dates.count

}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

    return dates[row]    
}

Solution

  • You need to reload the picker view inside the getObjectInBackgroundWithId block/closure, which is called asynchronously. I don't know if that completion block runs on a background queue or the main queue, but if it's the former, you'll have to also dispatch the reload back to the main queue.