【发布时间】:2020-05-01 18:14:45
【问题描述】:
我创建了一个带有原型单元格的 tableView。在这些原型单元中的每一个内部都有另一个具有不同原型单元的 tableView。我已经很好地将这一切联系在一起,但是我在修改最里面的原型单元格时遇到了麻烦。这就是为什么。 以下是相关代码:
class ViewController: UIViewController, AVAudioRecorderDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "outerCell") as! outerCell
//would obviously make some modification to cell here, like cell.title = "test" or something
let cell2 = cell.commentTableView.dequeueReusableCell(withIdentifier: "innerCell") as! innerCell
cell2.commentText.text = "sus"
//NEED TO DIFFERENTIATE HERE ON HOW TO KNOW WHICH CELL TO RETURN
//e.g. NEED TO RETURN either cell1 or cell2, depending on the tableView
}
outerCell 的代码如下所示:
import UIKit
class outerCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var commentTableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
commentTableView.delegate = self
commentTableView.dataSource = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "innerCell", for: indexPath) as! commentCell
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
}
看,主要问题是,这两个表视图都可以正常工作,但是,在第一段代码中,如果我只是执行类似的操作,
if tableView == self.tableView{
return cell }
else ...
这行不通,因为 tableView 似乎总是 self.tableView。
如何修改我的代码,以便在同一代码块中实际影响内部单元格和外部单元格中显示的文本?
另外,请注意,我知道,根据此处给出的示例,不需要这些嵌套单元格。我只是简化了这里的代码以专注于重要的事情 - 我的实际代码在内部和外部单元格中都有很多事情发生。
谢谢你,任何帮助将不胜感激。
【问题讨论】:
-
您需要将
outerCell的dataSource(在您的情况下可能是delegate)设置为您的ViewController实例。 -
啊,好吧,我该怎么做?
-
例如我写什么而不是 tableView.delegate = self
-
我不肯定这会起作用,但在
func tableView(_:cellForRowAt:)->UITableViewCell下面的let cell = ...行中,设置cell.dataSource = self和cell.delegate = self。 -
"我已经创建了一个带有原型单元格的 tableView。每个原型单元格内部都有另一个带有不同原型单元格的 tableView。" 如果您有两个 table view 对象,为什么只有一个 IBOutlet-那么连接tableView对象呢?
标签: ios swift uitableview indexpath