【问题标题】:indexPath is nil when passing cell from delegate to UITableViewController将单元格从委托传递到 UITableViewController 时 indexPath 为零
【发布时间】:2020-02-29 00:01:46
【问题描述】:

我在 tableView 的每个部分的末尾都有一个名为 addSet 的按钮,它用作 footerView,它应该告诉 UITableViewController 何时按下它以及在哪个部分。我的自定义表格视图单元格代码如下

import UIKit

class FooterTableViewCell: UITableViewCell {


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

    }

    var footerDelegate:FooterTableViewCellDelegate?

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }



    @IBAction func addSetIsPressed(_ sender: AnyObject) {

        print("Add Set is pressed")

        footerDelegate?.didAddSetIsPressed(cell:self)
    }



}

protocol FooterTableViewCellDelegate {

    func didAddSetIsPressed(cell:FooterTableViewCell)
}

在我的 TableViewController 中,我是这样实现的

func didAddSetIsPressed(cell: FooterTableViewCell) {

    let indexPath = tableView.indexPath(for: cell)

    print("Index path is \(indexPath)")
}

我想在用户点击我的按钮时获取 indexPath(具体的部分),但它总是返回 nil。我究竟做错了什么?

把事情放在上下文中。我使用这个单元格作为footerView,所以单元格是这样实现的

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

    let cell = tableView.dequeueReusableCell(withIdentifier: "footerCell") as! FooterTableViewCell
    cell.footerDelegate = self


    return cell
}

所以它没有像通常那样在 indexPath 的 cellForRow 中实现

提前致谢。

【问题讨论】:

    标签: ios swift xcode uitableview


    【解决方案1】:

    问题是您将单元格FooterTableViewCell 设置为viewForFooterInSection, 所以 它不被用作 UITableViewCell UITableView,所以UITableView 没有持有这个UITableViewCellindexPath“因为我说以前,单元格的视图仅用作 footerView"

    您需要在UITableView 上呈现的单元格内添加按钮。 "tableView(_:cellForRowAt:) 方法中返回的那个"

    在旁注中,我注意到您的单元格中有一个名为 footerDelegate 的变量,它需要是 weak 以避免内存泄漏,因为您将 TableViewController 分配为此委托, 所以UITableViewCell 持有TableViewController 的强引用,这会导致内存泄漏,同样在视图层次结构中TableViewController 包含UITableView 作为子视图。

    【讨论】:

    • 是的,但问题是我已经在 indexPath 中使用了函数 cellForRow 以及必须在每个部分中显示的单元格,那么如何将这个函数用于我的行和页脚?
    【解决方案2】:

    我发现了如何做到这一点,以便检测点击按钮的部分。在FooterCell和tableViewController中必须有outlet引用,在Section的viewForFooter中,添加如下一行即可

    cell.addSetOutlet.tag = section
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2018-05-07
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多