Search code examples
swiftbuttonuipickerviewviewcontroller

How can i navigate to another view controller dependent on a variable


I am trying to link to another view controller by pressing a button which i have named 'find'. The issue is with the pickerView. i want the 'service' selected from the pickerView to determine which page you end up on. For example, you select 'bars' in the pickerView, you click the 'find' button and it takes you to the bars view controller page.

Here is my code which controls the picker and the find button.

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate {

@IBOutlet weak var SelectedService: UILabel!

@IBAction func Find(sender: AnyObject) {

}


@IBOutlet weak var ItemLabel: UILabel!



var services = ["Cafe","Coffee Shops","Bar","Takeaway","Sunday Roast","Shoe Mender","Craft Shops","Electrical"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.








}

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 services.count   
}

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

    return services[row]
}

}

I am new to coding with swift so please could you explain your answer in a simple way.

Thank you very much

Shaun


Solution

  • In @IBAction func Find() you could have switch statement where you check which item from UIPickerView was selected, and based on that you can present desired view controller like this:

    let cafeViewController: CafeViewController = CafeViewController()
    self.presentViewController(cafeViewController, animated: true, completion: nil)
    

    But are you sure you need it's own view controller for every item? They'll probably look exactly the same, only presented data will be different... so you could use just one view controller, send picked item in func prepareForSegue() and according on that prepare data in viewDidLoad() in that view controller.

    Or at least try to reuse as much as you can creating some base class for your view controller and then create subclass for each service.