我正在尝试在 Swift 中构建一个通用的 UITableViewController 子类,它可以容纳任意数量的不同类型的表格视图单元格,而无需了解它们中的任何一个。
为此,我尝试为我的模型和表格视图单元格使用协议。模型的协议将返回我应该去哪个单元格类别,而单元格的协议将返回对给定模型的单元格高度应该是多少等问题的答案。
但是我在使协议工作时遇到问题,因为使用第二个协议我想进入单元的类而不是它的实例。
模型的协议如下:
protocol JBSTableItemDelegate
{
func tableCellDelegate() -> JBSTableViewCellInterface
}
细胞的协议如下:
protocol JBSTableViewCellInterface: class
{
static func registerNibsWithTableView(tableView: UITableView)
static func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath?, tableItem: JBSTableItemDelegate) -> CGFloat
static func tableView(tableView: UITableView, dequeueReusableCellWithIndexPath indexPath: NSIndexPath, tableItem: JBSTableItemDelegate, delegate: AnyObject) -> JBSTableViewCell
}
注意关键字“static”的使用。这些方法是 UITableViewCell 子类中的类方法,添加静态似乎是我需要做的来验证这些类是否符合,或者我理解。
当我使用第一个协议时,代码看起来像这样,它编译:
let tableViewCellInterface = tableItem!.tableViewCellInterface()
它正在调用此方法(作为一个示例):
func tableViewCellInterface() -> JBSTableViewCellInterface
{
return JBSLiteratureTableViewCell.self as! JBSTableViewCellInterface
}
这将返回单元格的类,例如“JBSLiteratureTableViewCell.self”
当我使用第二个协议时,代码看起来像这样,并且无法编译:
returnFloat = tableViewCellInterface.tableView(tableView, heightForRowAtIndexPath: indexPath, tableItem: tableItem!)
由于之前的 static 关键字,它无法编译,我得到的编译器错误是:
“JBSTableViewCellInterface”没有名为“tableView”的成员
如果我从协议函数中取出静态关键字,它会编译,但是 UITableViewCell 子类抱怨说:
“JBSLiteratureTableViewCell”不符合协议“JBSTableViewCellInterface”
这是因为他们现在正试图确保实例方法存在,而这些方法并不存在。
如何使 swift 类符合类级别的协议,所以它可以是我的委托而不是类的某个实例?我确信我可以通过创建作为单例的协议 JBSTableViewCellInterface 的帮助程序类并让它们完成工作来解决这个问题,但我宁愿将它直接构建到其类方法中的 UITableViewCell 子类中。