将数据传递给 Swift 中的另一个 ViewController

Passing data to another ViewController in Swift

在开始之前,让我先说一下,我已经看过一个关于此事的热门post:Passing Data between View Controllers

我的项目在githubhttps://github.com/model3volution/TipMe

我在 UINavigationController 中,因此使用 pushsegue。

我已验证我的 IBAction 方法已正确链接并且 segue.identifier 对应于情节提要中的 segue 标识符。

如果我取出 prepareForSegue: 方法,则会发生 segue,但显然没有任何数据更新。

我的具体错误信息是: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)"
    }

}

下面是包含代码和错误的屏幕截图。 旁注:使用 Xcode 6.3,Swift 1.2

几件事:

1:将您的 prepareForSegue 更改为

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

2: 添加一个字符串变量到你的 FacesViewController

var text:String!

3:改变FacesViewControllerviewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    balanceLabel.text = text
}

所有更改的原因:segue destinationViewController 是您转换到的实际 FacesViewController -> 不需要 navigationController 恶作剧。仅此一项就会删除 "case error",但由于解包 nil 值会发生另一个,因为您尝试访问尚未设置的 balanceLabel。因此,您需要创建一个字符串变量来保存您实际想要分配的字符串,然后在 viewDidLoad 中分配该文本 - 在 UILabel 实际分配的位置。

它有效的证明:

4:如果你想显示两位小数的余额,你可以将字符串创建更改为类似(在 之后):

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

导致: