bananibau5 bananibau5 - 3 months ago 29
Swift Question

Determine Segue Based on picker selection IOS, swift

I have a picker with two options currently, and what I am looking for is, based on the selection made in the picker, to determine the next viewController below is what I tried to use however, I immediately got an error stating the last "if" statement should be converted into a let statement. Below is the code for my picker and attempt to lead into associated segue.

import UIKit
import Firebase
import CoreData
import CoreLocation

class SchoolPickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var SchoolPicker: UIPickerView!
let pickerData = ["Ohio State University", "University of Rochester"]
override func viewDidLoad() {
super.viewDidLoad()
SchoolPicker.dataSource = self
SchoolPicker.delegate = self
// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}

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

@IBAction func schoolSelectorGoButton(sender: AnyObject) {
if pickerData = "Ohio State University" {
performSegueWithIdentifier("ohioStateSelected", sender: sender)
}
if pickerData = "University of Rochester" {
performSegueWithIdentifier("rochesterSelected", sender: sender)
}
}


}

Answer

u should get selected picker data from Array

define

var selectedIndex = 0

then in this line

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

and in this action

@IBAction func schoolSelectorGoButton(sender: AnyObject) {
    if pickerData[selectedIndex] == "Ohio State University" {
        performSegueWithIdentifier("ohioStateSelected", sender: sender)
    }
}
Comments