bk. bk. - 1 year ago 104
iOS Question

Getting data from a different ViewController in Swift

I have a PickerView which has different office choices and I want to reach this office references as

in another
. My
class :

import UIKit
class PickerViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet weak var officePicker: UIPickerView!

let offices = ["Choice 1","Choice 2","Choice 3"]
override func viewDidLoad() {

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

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let value = offices[row]

I have a home screen which has office informations. I want to add office info which selected before with using PickerView to this screen from a database with comparing the office names.

Answer Source

You can store your selected picker in a variable String. First declare it.

var selectedOffice: String?

In your pickerView delegate, just assign that variable.

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
      let value=offices[row]
      selectedOffice = value

When you're ready to go to next view controller, the simplest way is to pass the data with that viewcontroller. Before that, just create another variable in the viewcontroller that you want.

var selectedOffice: String?

In your current view controller and when you want to go to next controller, assign the variable as shown below as example.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = self.storyboard!.instantiateViewControllerWithIdentifier("frontView") as! FrontViewController
vc.selectedOffice = selectedOffice
self.navigationController?.pushViewController(vc, animated: true)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download