我想确保我的tableview只包含符合所述协议的单元格。我简化了实现以说明具体问题。
!vi
上面的代码是有效的,只是有重复的代码,我每次都需要进行转换来访问configureMyLookAndFeel()方法。因为我希望我的所有单元格都配置为外观和感觉,我尝试了下面的代码,但是遇到了编译错误
错误:无法将'protocol'类型的返回表达式转换为返回类型'UITableViewCell'
protocol ACommonLookAndFeel {
func configureMyLookAndFeel()
}
CellA: UITableViewCell, ACommonLookAndFeel
CellB: UITableViewCell, ACommonLookAndFeel
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell
if indexPath.row == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("CellA", forIndexPath: indexPath) as! CellA
if let myCell = cell as? CellA {
myCell.configureMyLookAndFeel() // we need to call this for each cell
}
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCellWithIdentifier("CellB", forIndexPath: indexPath) as! CellB
if let myCell = cell as? CellB {
myCell.configureMyLookAndFeel() // we need to call this for each cell
}
}
return cell
}
有没有办法解决这个编译错误?
理想情况下,我不想避免重复调用dequeueCell和强制转换为 CellA 或 CellB 。基于 cellReuseIdentifier ,我知道我需要将它投射到哪个单元格,这与我的单元格类名称相同。有办法吗?
谢谢!
答案 0 :(得分:1)
试试这个:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell
if indexPath.row == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("CellA", forIndexPath: indexPath) // There is no need to cast here
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCellWithIdentifier("CellB", forIndexPath: indexPath) // There is no need to cast here
}
// The method will be called for all cells that conform to ACommonLookAndFeel.
// This is also safe, so no crash will occur if you dequeue a cell that
// doesn't conform to ACommonLookAndFeel. Depending on the behavior
// you want to achieve, you may want to use a ! instead of ? to force
// a crash in case of issues while developing your app.
(cell as? ACommonLookAndFeel)?.configureMyLookAndFeel()
// You have to return a UITableViewCell, not a ACommonLookAndFeel
return cell
}