继承功能

时间:2016-02-20 17:43:22

标签: ios swift

除了一些细节之外,我正在尝试使用UITableViewCell以及UICollectionViewCell几乎完全相同的功能。我想创建一个这两个可以继承的超类,但无法弄清楚如何去做。我已使用UITableViewController超类为UICollectionViewControllerUIViewController完成了此操作。每个子类都是UIViewController类型,它有适当的委托/数据源方法。但是,UITableViewCellUICollectionViewCell没有数据源/委托方法。我怎样才能做到这一点? 谢谢!

2 个答案:

答案 0 :(得分:0)

您不需要UITableViewCellUICollectionViewCell的任何进一步协议声明。

分别从每个子类创建一个基类,并实现您需要的方法。

然后通过从基类

创建子类来使用它们

例如:

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"

......表明他们都做了同样的事情,没有重复代码。