我想确保我的表格 View 只包含符合所述协议(protocol)的单元格。我简化了实现以说明具体问题。
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
}
上面的代码是有效的,除了有重复的代码,我每次都需要进行转换才能访问 configureMyLookAndFeel() 方法。因为我希望我的所有单元格都针对外观进行配置,所以我尝试了下面的代码,但遇到了编译错误
错误:无法将类型“协议(protocol)”的返回表达式转换为返回类型“UITableViewCell”
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: protocol <ACommonLookAndFeel>
if indexPath.row == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("CellA", forIndexPath: indexPath) as! CellA
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCellWithIdentifier("CellB", forIndexPath: indexPath) as! CellB
}
cell.configureMyLookAndFeel() // works
return cell // Compiler Error !
}
有没有办法修复这个编译器错误?
理想情况下,我不想避免重复调用 dequeueCell 和转换为 CellA 或 CellB。我知道我需要根据与我的单元格类名称相同的 cellReuseIdentifier 将其转换到哪个单元格。有办法吗?
谢谢!
最佳答案
试试这个:
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
}
关于ios - 如何使符合已定义协议(protocol)的 UITableViewCells 出队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38441310/