Passing data to another ViewController in Swift

4.2k Views Asked by At

Before I begin, let me say that I have taken a look at a popular post on the matter: Passing Data between View Controllers

My project is on github https://github.com/model3volution/TipMe

I am inside of a UINavigationController, thus using a pushsegue.

I have verified that my IBAction methods are properly linked up and that segue.identifier corresponds to the segue's identifier in the storyboard.

If I take out the prepareForSegue: method then the segue occurs, but obviously without any data updating.

My specific error message is: Could not cast value of type 'TipMe.FacesViewController' (0x10de38) to 'UINavigationController' (0x1892e1c).

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
    if segue.identifier == "toFacesVC" {
        let navController:UINavigationController = segue.destinationViewController as! UINavigationController
        let facesVC = navController.topViewController as! FacesViewController
        facesVC.balanceLabel.text = "Balance before tip: $\(balanceDouble)"
    }

}

Below is a screenshot with the code and error. side notes: using Xcode 6.3, Swift 1.2 screen shot with code and error

1

There are 1 best solutions below

7
On BEST ANSWER

A couple of things:

1: change your prepareForSegue to

if segue.identifier == "toFacesVC" {
    let facesVC = segue.destinationViewController as! FacesViewController
    facesVC.text = "Balance before tip: $\(balanceDouble)"
}

2: add a string variable to your FacesViewController

var text:String!

3: change the FacesViewController viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    balanceLabel.text = text
}

The reasons for all the changes: the segue destinationViewController is the actual FacesViewController you transition to -> no need for the navigationController shenanigans. That alone will remove the "case error", but another will occur due to unwrapping a nil value because you try to access the balanceLabel which will not have been set yet. Therefore you need to create a string variable to hold the string you actually want to assign and then assign that text in the viewDidLoad - at the point where the UILabel is actually assigned.

Proof that it works:

enter image description here

4: If you want display two decimal places for the balance you might change the String creation to something like (following https://stackoverflow.com/a/24102844/2442804):

facesVC.text =  String(format: "Balance before tip: $%.2f", balanceDouble)

resulting in:

enter image description here