pepe pepe - 2 months ago 10
Swift Question

Call a textfield from other view controller in swift (prepareforsegue)

I read a lot of posts and videos of this and I read that is with a function calls "prepareforsegue" but I donĀ“t understand where to implement and what other things do I have to do. I have 4 textfields that I want to call from another later controller. Thank you very much for the answer. :)

3li 3li
Answer

You can't set values or access to textfields or any other outlet inside prepareforsegue method. That because prepareforsegue method is called "before" the destination controller's outlets get set. So you need to create a variable in your destination controller that receives the value for the textfield and then in viewDidLoad in destination controller set it to the textfield.

In prepareforsegue method :

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let destinationViewController = segue.destinationViewController as? SecondViewController {
        destinationViewController.valueForTextField = "Hi"
    }
}

In the destination controller (which is SecondViewController in my case) :

@IBOutlet weak var textField: UITextField!
var valueForTextField: String?
override func viewDidLoad() {
    super.viewDidLoad()
    textField.text = valueForTextField
}
Comments