Home > Enterprise >  How to transfer UIPickerView between two viewcontrollers
How to transfer UIPickerView between two viewcontrollers

Time:10-11

Im very new to xcode. Im getting the user to select from a UIPicker view and when they click a submit button it goes to the next screen and displays what they chose. I got it to work with normal textboxes with segue code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController2 = segue.destination as?
ViewController2 {
viewController2.textstr = textField.text
}
}

but i dont really know to apply the same formula with UIPickers, Segments and Steppers

CodePudding user response:

You can use this:

class ViewController: UIViewController {

   var pickerValue = ""

   override func viewDidLoad() {
        super.viewDidLoad()

   }

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

      self.pickerValue = yourArray[row]
  }
}

And then:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "ViewController2" {
        if let dvc : ViewController2 = segue.destination as? ViewController2{
 
           dcv = self.pickerValue
     }
   }
}


  @IBAction func submitBtn(_ sender: Any) {
        
     self.performSegue(withIdentifier: "ViewController2", sender: self)
  }

CodePudding user response:

you can pass value from using thing code.

class ViewController: UIViewController {
    
    var selectedPickerValue: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if let viewController2 = segue.destination as? ViewController2 {
            viewController2.selectedValue = selectedPickerValue
        }
        
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        selectedPickerValue = //give value from you picker to this variable
        
    }
    
    
}

class ViewController2: UIViewController {

    var selectedValue: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

}

I hope you find it helpful. Best of luck

  • Related