我的偶然尝试没有调用 cellForRowAtIndexPath
。我假设我的设置不正确。
let wordTableView = WordTableView(frame: CGRectZero)
wordTableView.delegate = self
wordTableView.dataSource = self
wordTableView.words = words
let currentCell = wordTableView.cellForRowAtIndexPath(indexPath)
cell.contentView.addSubview(wordTableView)
wordTableView.viewDidLoad()
wordTableView.reloadData()
当我运行它时,我的 UITableView 的 viewDidLoad() 被调用。但实际上没有加载。如果查看 Debug View Hierarchy,我可以看到没有添加任何内容。所以我假设我遗漏了一些关于实例化此 tableView 的特殊内容。
作为引用,这是我的 UITableView。但老实说,我完全在猜测 UITableView 到底需要什么来实例化。这将是我最好的尝试:
class WordTableView: UITableView {
var words = [Word]()
func viewDidLoad() {
self.registerNib(UINib(nibName: "WordCell", bundle: nil), forCellReuseIdentifier: "wordCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("WordCell", forIndexPath: indexPath) as! WordCell
let word = words[indexPath.row]
cell.sanskrit.text = "Sanskrit" //word.valueForKey("sanskrit")
cell.definition.text = "Definition" // word.valueForKey("definition")
return cell
}
}
最佳答案
您将wordTableView
数据源和delegate设置给了setter类,所以table view数据源和delegate函数不会在WordTableView
类中被调用。
既然你说你的 viewDidLoad
被调用,让我们在这个函数中设置委托(delegate)。
let wordTableView = WordTableView(frame: CGRectZero)
wordTableView.words = words
let currentCell = wordTableView.cellForRowAtIndexPath(indexPath)
cell.contentView.addSubview(wordTableView)
wordTableView.viewDidLoad()
wordTableView.reloadData()
和WordTableView
类
class WordTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var words = [Word]()
func viewDidLoad() {
self.registerNib(UINib(nibName: "WordCell", bundle: nil), forCellReuseIdentifier: "wordCell")
self.delegate = self
self.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("WordCell", forIndexPath: indexPath) as! WordCell
let word = words[indexPath.row]
cell.sanskrit.text = "Sanskrit" //word.valueForKey("sanskrit")
cell.definition.text = "Definition" // word.valueForKey("definition")
return cell
}
}
作为旁注,您不应该直接调用 viewDidLoad()
,最好让 WordTableView
继承 UIViewController
并将您的里面的表格 View 。
关于ios - 在 UITableView 单元格中加载 UITableView 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36518182/