Reputation: 37
I have a label (in my secondVC) which is displaying a segued Double from the firstVC. In the secondVCs viewDidLoad I am printing the passedDouble
and it is printing the correct amount, so I know my Double is being segued correctly. My UILabel
is in the secondVC and only shows an amount if the passedDouble
= 0.0.
SecondViewController:
@IBOutlet weak var totalLabel: UILabel!
var passedDouble = 0.0
override func viewDidLoad() {
super.viewDidLoad()
print("testing for a value \(passedDouble)")
totalLabel.text = String("\(passedDouble)")
}
If the passed value is 12.2 for example, it prints this
testing for a value 12.2
But the label completely disappears from view.
If the passed value is 0.0 however, it prints
testing for a value 0.0
and the label shows 0.0
In the storyboard I have left the labels standard text as Label. So, I know the label is connected properly as it's text changes IF the value is nil.
EDIT: Code for the firstVC where I am assigning the value
var totalPrice: Double = Double()
@IBAction func basketAction(_ sender: UIButton) {
for cost in priceDictionaryToBeSent {
totalPrice += Double(cost)!
}
performSegue(withIdentifier: "basket", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "basket" {
if let basketVC = segue.destination as? BasketViewController {
basketVC.passedDouble = totalPrice
//This is sending the correct price
}
}
}
Upvotes: 0
Views: 56
Reputation: 37
Thank you to Milan Nosáľ for saying the view could've already loaded, indeed it had, so I moved the code from viewDidLoad
in my BasketViewController
to viewDidAppear
as seen below:
override func viewDidAppear(_ animated: true) {
super.viewDidAppear(true)
print("testing for total price £\(passedDouble)")
totalLabel.text = "Total price £\(passedDouble)"
}
Upvotes: 0
Reputation: 19737
My best guess is that in prepare(for:sender:)
the basketVC
's view
is already loaded, so its viewDidLoad
got called before you are setting basketVC.passedDouble = totalPrice
.
I would rather use setter to update the label everytime the passedDouble
gets updated. Change the BasketViewController
code to this:
@IBOutlet weak var totalLabel: UILabel!
var passedDouble = 0.0 {
didSet {
self.totalLabel?.text = "\(passedDouble)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// no need to set totalLabel.text here
}
Upvotes: 1