首页 > 解决方案 > 在子 TableView 中获取父单元格的 indexPath

问题描述

我目前有一个 TableView,它位于原型 TableViewCell 内。为了消除混淆,层次结构如下:

TableViewController
--> TableViewCell
    --> TableView

我正在尝试访问 TableView 所在的 indexPath.section,对于 TableViewController 中的每个不同单元格,我想在 TableView 中显示不同的数据。

我的代码目前如下:

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "todayCell", for: indexPath) as! MyTableViewCell

        // Configure the cell...
        switch indexPath.section {
        case 0:
            cell.label.text = "Today"
        case 1:
            cell.label.text = "Tomorrow"
        default:
            cell.label.text = "Error"
        }

        return cell
    }

}

对于我的 TableViewCell:


class MyTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var cancelButton: UIButton!
    @IBOutlet weak var completeButton: UIButton!

    var numOfRowsOne = 6
    var numOfRowsTwo = 7



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


    }

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

        // Configure the view for the selected state
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        var rows = 0
        if (TableViewController Cell's indexPath.section) == 0 {
            rows = numOfRowsOne
        } else {
            rows = numOfRowsTwo
        }

        return rows
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = todayTableView.dequeueReusableCell(withIdentifier: "activitiesCell", for: indexPath)

        return cell
    }

 }

谢谢!

标签: iosswiftuitableviewparent-child

解决方案


你可以得到indexPath如下,

if let ip = (self.superview as? UITableView)?.indexPath(for: self), ip.section == 0 {
    rows = numOfRowsOne
} else {
    rows = numOfRowsTwo
}

推荐阅读