2016-09-25 116 views
0

我正在Swift編寫一個Xcode程序。我有一個tableview控制器與一些標籤和每個單元格的圖像。他們從第一個視圖控制器獲取數據。到現在爲止還挺好。現在我想讓用戶點擊一個單元格,它打開一個新的控制器,其中包含與單元格相同的標籤和圖像數據。用下面的代碼打開新的控制器,但我不知道如何傳輸數據。如果有人能幫助我,我會如此感激。從tableview傳遞數據到視圖控制器

下面是我傾向於使用以下碼:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 


    let cellIdentifier = "TableView" 
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TableView 


    let picture = pic[indexPath.row] 



    cell.label1.text = picture.name1 
    cell.photoImage.image = picture.photo 
    cell.label2.text = picture.name2 


    return cell 


} 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 


    tableView.deselectRowAtIndexPath(indexPath, animated: true) 


    let cell = indexPath.row 

    self.performSegueWithIdentifier("segue", sender: cell) 

} 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

    if segue.identifier == "segue"{ 

     var row = tableView.indexPathForSelectedRow 

     let viewController = segue.destinationViewController as! vc2 

    } 

} 

PS:我有從圖像與識別符「SEGUE」的新控制器SEGUE。 PPS:當然,我曾嘗試以下方法:Send data from TableView to DetailView Swift但是當我運行我的程序我得到的信息的錯誤,我的標籤被意外發現零

+0

您是否已將您的標籤連接到ViewController中的IBOutlets? –

+0

是的,單元格中的標籤連接到tableviewcell文件,目標控制器中的標籤連接到他們的控制器 – j3a3n3

回答

0

你不應該需要重寫didSelectRowAtIndexPath方法或致電performSegueWithIdentifier做到這一點。將IBue文件中的segue從表視圖控制器的單元格拖到第二個控制器。然後,您應該將數據傳遞給prepareForSegue中的控制器,位於segue.destinationViewController中。您在該目標控制器上設置公共屬性。

還要確保您的原型單元格中的標籤已連接到IB。如果他們是他們,不應該是零。在cellForRowAtIndexPath上設置一個斷點來驗證這一點。

除非您正在談論目標控制器中的標籤。這些也需要與IB聯繫起來。然後你將它們設置爲prepareForSegue。您會從

let viewController = segue.destinationViewController as! vc2 
var path = tableView.indexPathForSelectedRow 

viewController.destLabel.text = arrayData[path.row].myData // or whatever data you have from your model. 
+0

我按照您的建議操作。數據仍未傳輸。此外,我現在得到一個錯誤(標籤發現零)時試圖創建一個額外的單元:( – j3a3n3

相關問題