除了一些细节之外,我正在尝试使用UITableViewCell
以及UICollectionViewCell
几乎完全相同的功能。我想创建一个这两个可以继承的超类,但无法弄清楚如何去做。我已使用UITableViewController
超类为UICollectionViewController
和UIViewController
完成了此操作。每个子类都是UIViewController
类型,它有适当的委托/数据源方法。但是,UITableViewCell
或UICollectionViewCell
没有数据源/委托方法。我怎样才能做到这一点?
谢谢!
答案 0 :(得分:0)
您不需要UITableViewCell
和UICollectionViewCell
的任何进一步协议声明。
分别从每个子类创建一个基类,并实现您需要的方法。
然后通过从基类
创建子类来使用它们例如:
class BaseTableViewCell: UITableViewCell {
@IBOutlet var foo : UILabel!
var bar = false
func method1() {}
func method2() {}
}
class MySpecialTableViewCell: BaseTableViewCell { }
答案 1 :(得分:0)
您可以使用协议和协议扩展将相同的功能注入到这两个类中:
@objc protocol MyProto {
func someFunc()
}
extension MyProto {
func someFunc() {
print("howdy")
}
}
class MyTableViewCell : UITableViewCell, MyProto {
}
class MyCollectionViewCell : UICollectionViewCell, MyProto {
}
let cell1 = MyTableViewCell()
cell1.someFunc() // "howdy"
let cell2 = MyCollectionViewCell()
cell2.someFunc() // "howdy"
......表明他们都做了同样的事情,没有重复代码。