[英]Swift: Passing data from a tableView in a ViewController to another 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.