0
votes

I am trying to load items into UIPickerView, these items are loaded from a list that is populated in a prepareforsegue function in a previous view

class AddItemViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {


    @IBOutlet weak var ItemPickView: UIPickerView!
    @IBOutlet weak var textboxName: UITextField!

    var options: [String]?
    var name: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewdidload started")
        ItemPickView.delegate = self
        ItemPickView.dataSource = self
        textboxName.inputView = ItemPickView
        print("viewdidload ended")
        print(options)
    }

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

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        options!.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return options![row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        textboxName.text = options![row]
    }
}

My segue code

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "AddNewItem" {
        print("segue started")
        let controller = segue.destinationViewController as? AddItemViewController
        controller?.options = ["test1","test2","test3"]
        print("segue ended")
    }
 }

It seems that the UIPickerView is initiated before the list is changed. Any workaround for this?

Thanks a lot

Edit: here is the log from print statments

segue started
segue ended
viewdidload started
viewdidload ended
nil
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

It seems segue finishes before viewdidload.. then why isn't options list updated?

1
code is correct. did you debug ? is the code going in the if condition of prepareForSegueShubhank
yes the code is running correctly, print statements do print... but the viewDidLoad seems to run before the segue code.. also viewDidAppear did not helpAnya Alstreim
your code do not have print statements. please update your code with them and then show the log output sequenceShubhank
log the options var too in viewDiDLoadShubhank

1 Answers

0
votes

One way is to tag the fileowner as the datasource and delegate[ in the XIB ]. This way there is no need to wait did View didload to attach the necessary data source and delegate.