[英]Handling multiple subclasses of UITableViewCell within a table
我正在详细视图控制器内构建UITableView
。 该表视图的某些方面包括:
PhotoCell
和InfoCell
,它们都扩展了UITableViewCell
。 UITableViewCell
每个子类中,我创建了一个static createCell()
方法,该方法使用tableView.dequeueReusableCellWithIdentifier
返回初始化的,填充的单元格。 dequeueReusableCellWithIdentifier
是否可以接受(甚至有用)? 我采用的方法是定义一个包含单元格数组的source
属性。 我不确定这是否是处理它的最佳方法。
PlaceViewController + UITableViewDataSource.swift
extension PlaceViewController: UITableViewDataSource {
var source: [UITableViewCell] {
get {
var cells = [UITableViewCell]()
if let cell = SummaryCell.createCell(tableView, text: place?.generalInfo) {
cells.append(cell)
}
// ^^ repeat above for each cell in table
return cells
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return source[indexPath.row]
}
}
SummaryCell.swift
class SummaryCell : UITableViewCell {
@IBOutlet var summaryLabel: UILabel!
static func createCell(tableView: UITableView, text: String?) -> SummaryCell? {
if let text = text {
let cell = tableView.dequeueReusableCellWithIdentifier("SummaryCell") as! SummaryCell
cell.summaryLabel.text = text
return cell
}
return nil
}
}
如果您为表使用不同的单元格,则不妨进行条件检查或切换特定索引中所需的单元格类型,然后尝试确定是否已创建了这种类型的单元格-如果未初始化新的单元格。
另外,查看您的代码,每当调用cellForRowAtIndexPath的调用时,您都将创建一个新的单元格数组,这不好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.