【问题标题】:How to transfer value after clicking a button in a UITableviewCell?单击 UITableviewCell 中的按钮后如何传输值?
【发布时间】:2016-11-22 16:00:25
【问题描述】:

ViewController 中有一个 TableView。TableViewCell 有一个带有一些内容的 textView。现在单击cell 中的replyButton 后,segue 到secondViewController。我需要将内容放在cell 的textView 中。怎么做?我使用indexPath 作为下面的代码,但它崩溃了,因为indexPath 是nil。感谢您的帮助。

澄清:我需要点击单元格内的replyButton来实现目标,而不是使用didSelectRowAtIndexPath函数。

代码:

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

    */    
       }
 }


}

【问题讨论】:

  • 是否有任何崩溃报告或只是值 nil ?给我们一些关于您的问题的解释。
  • 因为 indexPath 为 nil 而崩溃。

标签: swift uitableview segue


【解决方案1】:

你需要使用一个协议,在Replycell.swift类之前添加这个

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

在类里面添加这个

weak var delegate: ReplycellDelegate?

在单元格中的按钮操作内添加此

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

现在在 uitableviewdatasource 之后的 ViewController 类中添加 RepplyCellDelegate,然后您只需调用函数didPressButtonFromCell 并且 Xcode 将为您自动完成它,当单元格的按钮被按下时,该函数将被调用,如果您有视图控制器中单元格的内容将一个 id 变量添加到 Repplycell 类,以便您可以在创建时将其传递给每个单元格,如果您在 Replycell 类中获取文本,而不是协议中的 id,则声明一个字符串并将其发送到 ViewController。

【讨论】:

    【解决方案2】:

    您尝试获取文本值的方式并没有太大问题,您只是在错误的函数中执行此操作。 UITableView 有一个函数didSelectRowAt:indexPath 可以工作。

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
            let cell = tableView.cellForRow(at: indexPath) as! Replycell
            replyVC.replyQuote = cell.replyTextView.text
    
    
        }
    

    【讨论】:

    • 你好埃里克,我明白你的意思。我需要单击单元格内的回复按钮,而不是整个单元格本身。所以我没有使用 didSelectRowAt indexPath 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2019-03-18
    相关资源
    最近更新 更多