的問題是,你在行
var destination = SecondViewController()
創建一個新的ViewController
但隨後的控制器只是重新分配,因爲沒有指向它(有它沒有提到它掉出來的範圍)。你還沒有進入它,也沒有進行任何繼續。
如何解決?基本上有兩種選擇。
故事板
如果你在故事板的工作,你必須創建第一ViewController
和SecondViewController
之間的SEGUE。你必須給它一個identifier
。
然後在didSelectRowAtIndexPath
你會寫
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(fruits[row])
self.toPass = fruits[row]
performSegueWithIdentifier("YOUR_SEGUE_IDENTIFIER", sender: nil)
}
然後prepareForSegue
你的屬性設置爲目的地SecondViewController
。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "YOUR_SEGUE_IDENTIFIER" {
let destVC = segue.destinationViewController as! SecondViewController
destVC.vieSegue = self.toPass!
}
}
手冊推
第二個選項是將didSelectRowAtIndexPath
方法
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(fruits[row])
let destination = SecondViewController()
destination.vieSegue = fruits[row]
// if you are using navigation controller
navigationController?.pushViewController(destination, animated: true)
// if you want to present it modally
// presentViewController(destination, animated: true, completion: nil)
}
第二個版本不強迫你創建塞格斯中手動推控制器。
爲什麼你的prepareForSegue是空的? –
嘿,通常你有類似 - >重寫func prepareForSegue(segue:UIStoryboardSegue,sender:AnyObject?){ super.prepareForSegue(segue,sender:sender); something = Something(); 讓vc = segue.destinationViewController as! YourViewController; vc.setSomething(something); } –