簡體   English   中英

在 Swift 中將數據傳遞給另一個 ViewController

[英]Passing data to another ViewController in Swift

在我開始之前,讓我說我已經看過一篇關於這個問題的熱門帖子: 在視圖控制器之間傳遞數據

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

我在一個 UINavigationController 里面,因此使用了push segue。

我已驗證我的IBAction方法已正確鏈接並且segue.identifier對應於故事板中的 segue 標識符。

如果我取出prepareForSegue:方法, prepareForSegue:發生轉場,但顯然沒有任何數據更新。

我的具體錯誤消息是: 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:改變FacesViewController viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    balanceLabel.text = text
}

所有更改的原因:segue destinationViewController是您轉換到的實際FacesViewController -> 不需要 navigationController 惡作劇。 僅此一項即可消除“案例錯誤”,但由於您嘗試訪問尚未設置的balanceLabel ,因此balanceLabel nil 值會發生另一個錯誤。 因此,您需要創建一個字符串變量來保存您實際想要分配的字符串,然后在viewDidLoad分配該文本 - 在UILabel實際分配的位置。

證明它有效:

在此處輸入圖片說明

4:如果您想顯示余額的兩位小數,您可以將字符串創建更改為類似(遵循https://stackoverflow.com/a/24102844/2442804 ):

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

導致:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM