Search code examples
swiftbuttonuiviewcontrolleruipickerview

Open new view controller page according to value chosen from UIPickerView (Swift 4)


I would like to add a function in my app where the user has to choose a category from a UIPickerView and upon clicking a button, the program would open the view selected from the categories in the UIPickerView. For example, if one of the chosen options on the UIPickerView is "About Page", I would like to have a program that would open the "About Page" upon a click of the button.

This is what the UI would look like.enter image description here

But instead of the states - I would have the categories, I'm not sure how to set the values in the UIPickerView and open specific views.


Solution

  • Implement UIPickerViewDelegate method and give each VC a stroryboard Identifier

    var lastId:String?
    
    var ids = ["secondVC","thirdVC"] // picker data source and identifier names 
    
    func pickerView(_ pickerView: UIPickerView, 
            didSelectRow row: Int, 
             inComponent component: Int) {
       lastId = ids[row]
    }
    
    @IBAction func goClicked(_ sender:UIButton) {
        if let id = lastId {
          let vc = storyboard.instantiateViewController(withIdentifier:id)!
          self.present(vc, animated: true, completion: nil) // or push
        }
        else {
          // select a vc alert
        }
    }