Reputation: 406
I created a UILabel
called order1label
on my ThirdViewController
.
I want text to be displayed on that label based on what is decided in my SecondViewController
.
Below is the code for those two view controllers. When I click on the Submit UIButton in the SecondViewController
, I expect the orderType
to change to Delivery
on the ThirdViewController
, and I expect that to be reflected in order1label
, but it is not. It still says Takeout
.
What am I doing incorrectly? I've been searching for answers for hours and there does not appear to be a simple solution to this extremely simple problem.
import UIKit
class SecondViewController: UIViewController{
var orderType = "Takeout"
@IBAction func SubmitOrderClicked(sender: UIButton) {
orderType = "Delivery"
}
}
Here is the code for my ThirdViewController
:
import UIKit
class ThirdViewController: UIViewController {
var orderTextController = SecondViewController().orderType
override func viewDidLoad() {
super.viewDidLoad()
order1Label.text = orderTextController
}
override func viewWillAppear(animated: Bool) {
order1Label.text = orderTextController
}
@IBOutlet var order1Label: UILabel!
}
Upvotes: 2
Views: 85
Reputation: 5467
Declare a global variable orderType
in SecondViewController
like:
import UIKit
var orderType = "Takeout"
class SecondViewController: UIViewController{
@IBAction func SubmitOrderClicked(sender: UIButton) {
orderType = "Delivery"
}
}
Here is the code the ThirdViewController:
import UIKit
class ThirdViewController: UIViewController {
override func viewWillAppear() {
super.viewWillAppear()
order1Label.text = orderType
}
@IBOutlet var order1Label: UILabel!
}
Hope this satisfies your requirements. Happy coding.
Upvotes: 1
Reputation: 64
your problem is only because the label in thirdController needs to be informed after the text is changed in secondController. After changed your text by clicking the button, you need to inform the label in thirdController to also change the text. There are several ways that you can achieve that, delegate, notification, block and so on. If you have further question about using any of ways above please tell me.
Upvotes: 0
Reputation: 485
I'm supposing that you want to present ThirdViewController when tapping the button on SecondViewController, so you'd need to change the code to:
import UIKit
class SecondViewController: UIViewController{
var orderType = "Takeout"
@IBAction func SubmitOrderClicked(sender: UIButton) {
orderType = "Delivery"
let thirdController = ThirdViewController()
thirdController.order1Label.text = orderType
self.present(thirdController, animated: true, completion: nil)
}
}
When you call present, the view controller you specify will load and will enter to viewDidLoad. You'd also need to remove this
var orderTextController = SecondViewController().orderType
Upvotes: 1