Search code examples
iosiphoneswiftuipickerviewibaction

Swift UIPickerView Trigger Segue with IBAction


I am new to Swift and could use some advice on how to trigger a segue using an IBAction on button click. I'm able to segue using the picker however I want the button to trigger the segue. I tried triggering the function inside the IBAction but that isn't working. Appreciate any advice. Thanks.

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    switch (row) {

    case 0: self.performSegueWithIdentifier("Segue0", sender: self)
    break;
    case 1: self.performSegueWithIdentifier("Segue1", sender: self)
    break;
    case 2: self.performSegueWithIdentifier("Segue2", sender: self)
    break;
    case 3: self.performSegueWithIdentifier("Segue3", sender: self)
    break;
    case 4: self.performSegueWithIdentifier("Segue4", sender: self)
    break;
    default: break;

    }

Here's the standard button:

@IBAction func selectButton(sender: AnyObject) {


}

Solution

  • If all you're looking for is how to determine which row is selected from within the button function, you can use UIPickerView.selectedRowInComponent(_:):

    @IBOutlet weak var picker: UIPickerView! // Reference to picker from storyboard. 
    @IBAction func selectButton(sender: AnyObject) {
        // Get the selected row. You only have one component, so the parameter is 0.
        let row = picker.selectedRowInComponent(0)
    
        // Switch block here
    }
    

    If in fact your segues are actually named "Segue0", "Segue1", etc., then you can replace the switch block with:

    self.performSegueWithIdentifier("Segue\(row)", sender: self)
    

    However, if you're using more descriptive segue names (as I hope you are), then you could also store the segue identifiers in an array and just use row as an index to the array:

    let segues = ["thisIsASegue", "thisIsAnotherSegue", "etc"]
    
    // In the function:
    self.performSegueWithIdentifier(segues[row], sender: self)