2016-11-22 66 views
0

ViewControllerTableViewTableViewCell有一個textView與一些內容。在cellseguesecondViewController之間點擊replyButton後。我需要將內容放入celltextView。怎麼做?我使用indexPath作爲下面的代碼,但它崩潰,因爲indexPathnil。感謝您的幫助。單擊UITableviewCell中的按鈕後如何傳遞值?

說明:我需要單擊單元格內的replyButton來實現目標,而不是使用didSelectRowAtIndexPath函數。

enter image description here

代碼:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 


    @IBAction func replyButtonTapped(_ sender: Any) { 

    self.performSegue(withIdentifier: "toReplyVC", sender: self) 

} 


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    if segue.identifier == "toReplyVC" { 

     let replyVC = segue.destination as! ReplyVC 

    // code below did't work: 

    /* 

     let indexPath = self.repliesTableView.indexPathForSelectedRow 

      let cell = self.repliesTableView.cellForRow(at: indexPath!) as! ReplyCell 

      replyVC.replyQuote = cell.replyTextView.text 

    */  
     } 
} 


} 
+0

是否有任何崩潰報告或只值nil?給我們一些關於你的問題的解釋。 – emresancaktar

+0

墜毀,因爲indexPath爲零。 – developermike

回答

0

您需要使用的協議,在Replycell.swift類

protocol ReplycellDelegate: class { 
func didPressButtonFromCell(cellView: Replycell, id: int)} 

裏面的類之前添加此添加此

weak var delegate: ReplycellDelegate? 

單元格中的按鈕操作內加這個

delegate?.didPressButtonFromCell(cellView: self, id: 2) 

,現在在ViewController類中的uitableviewdatasource之後添加RepplyCellDelegate,然後你只需調用函數didPressButtonFromCell,Xcode就會爲你自動完成它,當按下單元格的按鈕時,該函數將被調用,如果你有cell視圖控制器中添加一個id變量到Repplycell類,這樣你就可以在創建時將它傳遞給每個單元格,如果你在Replycell類中獲得文本而不是協議中的id,則聲明一個字符串並將其發送給視圖控制器。

0

沒有太多的毛病,你試圖讓文本價值的方式,你只是做了錯誤的函數內。 UITableView有一個功能didSelectRowAt:indexPath它將工作。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

     let cell = tableView.cellForRow(at: indexPath) as! Replycell 
     replyVC.replyQuote = cell.replyTextView.text 


    } 
+0

你好埃裏克,我明白你的意思。我需要點擊單元格內的replyButton,而不是整個單元格。所以我沒有使用didSelectRowAt indexPath函數。 – developermike