0

I'm trying to pass data from a ViewController (let's call it ViewControllerA) to a ViewControllerB. I created the ViewControllers programmatically so I am not using the storyboard at all. I would like to display in a UILabel in the ViewControllerB what the user types in a UITextField in ViewControllerA. Is there any way I can do this programmatically? I'm just a beginner so give me the simplest solution you know because it is the easiest one to grasp for me. Thank you!

Think is a sample of the code

ViewControllerA:

import UIKit

class ViewControllerA: UIViewController {

   let player1: UITextField = {
    let p1 = UITextField()
    p1.placeholder = "Player"

    return p1
}()

let goButton: UIButton = {
    let go = UIButton(type: .system)
    go.setTitle("Go!", for: .normal)

    go.addTarget(self, action: #selector(Go), for: .touchUpInside)

    return go
}()



override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(player1)
    view.addSubview(goButton)


}

func Go() {
    let viewB = ViewControllerB()
    present(viewB, animated: true, completion: nil)
}

}

ViewControllerB :

import UIKit

class ViewControllerB: UIViewController {

let topLabel: UILabel = {
    let tl = UILabel()
    tl.textColor = UIColor.white

    return tl
}()




override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(topLabel)

}

}

(When the user presses the goButton, I'd like the topLabel.text in ViewControllerB to be equal to the player1.text of ViewControllerA)

tommsyeah
  • 17
  • 2
  • 9
  • 1
    So, (1) create `String!` property in B to hold the text; (2) before you call `present`, set that `String` property in B; (3) in `viewDidLoad` of B, take that `String` value and populate the `text` property of your label. See https://stackoverflow.com/a/41346389/1271826 of that link that Dávid shared with us. – Rob Jul 22 '17 at 00:57
  • Sorry @Rob I don't really understand the first two points.. 1) How do I create a "String! property" ? Do you mean like var string = String() ? 2) How do I set the String property in B before calling the present in A? – tommsyeah Jul 22 '17 at 01:53
  • Define `var player: String!` property in B. Then, `viewB.player = player1.text` before you present. And then, in `viewDidLoad` of B, `tl.text = player`. – Rob Jul 22 '17 at 04:26
  • It worked! Thank you Rob! The segue method seems to be the most common to pass data between ViewController, why? This method seems simpler to me – tommsyeah Jul 22 '17 at 12:03
  • Using segues offer quite a few advantages (write less code, WYSIWYG, ability to unwind, etc.), and using `prepare(for:sender:)` is the price one pays once you enjoy a code-free initiation of the segue. It’s now very rare to see the pattern you’ve employed here. – Rob Jul 23 '17 at 01:28

0 Answers0