ios - 在 Swift 中将数据传递给另一个 ViewController

标签 ios iphone swift uinavigationcontroller segue

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

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

我在 UINavigationController 中,因此使用了 pushsegue。

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

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

我的具体错误消息是:无法将类型“TipMe.FacesViewController”(0x10de38)的值转换为“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 screen shot with code and error

最佳答案

一些事情:

1: 将你的 prepareForSegue 改为

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

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

var text:String!

3: 更改FacesViewController viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    balanceLabel.text = text
}

所有更改的原因:segue destinationViewController 是您转换到的实际 FacesViewController -> 不需要 navigationController 恶作剧。仅此一项就可以消除“大小写错误”,但由于您尝试访问尚未设置的 balanceLabel ,因此会由于展开 nil 值而发生另一个错误。因此,您需要创建一个字符串变量来保存您实际想要分配的字符串,然后在 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

关于ios - 在 Swift 中将数据传递给另一个 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831070/

相关文章:

ios - SKStoreProductViewController 的奇怪行为

ios - NSURLConnection 代表。如何取消认证质询?

iphone - 如何验证 UITextField 的内容?

iphone - 向服务器发送图像数据(NSData)

iphone - Exc Bad Access 关闭 View Controller

ios - 如何在 swift 类中将变量设置为 self(class)? iOS 代码

iphone - 当副本更改时 NSDictionary 也会更改

swift - Swift 中的 Java BigDecimal

ios - swift:弱不能应用于导出

swift - 如何在 SpriteKit 的不同类中访问已更改的属性