2015-06-14 265 views
2
传递到另一个数据视图控制器

在我开始之前,让我说,我已经在流行后对此事采取一看:Passing Data between View Controllers斯威夫特

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

我的内一个UINavigationController,因此使用push segue。

我已验证我的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,雨燕1.2 screen shot with code and error

+0

正如另一条评论已经建议:在你的问题中包含代码。我现在为你做了这个,因为提供该项目下载到某处可以让其他用户更容易地帮助你。我喜欢那个:) +1 – luk2302

回答

3

几件事情:

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有心计。仅此一项就会消除“大小写错误”,但由于您尝试访问尚未设置的balanceLabel,因此将展开另一个零值,因为它将展开一个零值。因此,您需要创建一个字符串变量来保存您实际想要分配的字符串,然后在viewDidLoad中分配该文本 - 在UILabel实际分配的位置。

证明了它的工作原理:

enter image description here

4:如果你想为你可能会改变字符串创建到类似的信息(以下https://stackoverflow.com/a/24102844/2442804)余额显示小数点后两位:

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

产生于:

enter image description here

+0

我想他希望它是“$ 4.00”而不是“$ 4.0”。我不知道如何在Swift中完成它,但是在Objective C中,它返回一个'NSString'对象:'[NSString stringWithFormat:@“在tip之前的平衡:$。2f“,balanceDouble]' – DDPWNAGE

+0

可能不知道与他的实际问题没有任何关系,而且我不知道在字符串文字'\(...)'中做什么的方法' – luk2302

+0

我知道它与OP的问题没有多大关系,但我只是看着屏幕截图,“$ 4.0”让我有点生气 – DDPWNAGE