正在获取子表视图中父单元格的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
}
}

谢谢!

您可以获得如下indexPath

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

最新更新