【问题标题】:Swift: How to create a custom overridden UITableView with a generic type for its delegate?Swift:如何为其委托创建一个具有泛型类型的自定义覆盖 UITableView?
【发布时间】:2019-09-19 06:01:28
【问题描述】:

我想创建一个 UITableView,并使用这个新的委托。基本上:

class GenericTableView: UITableView {    
    weak var customDelegate: GenericTableViewDelegate?
}

protocol GenericTableViewDelegate : NSObjectProtocol {
    func genericTableView(_ genericTableView: GenericTableView, numberOfRowsInSection section: Int) -> Int
}

但现在我想添加一个与该委托关联的泛型类型:

protocol GenericTableViewDelegate : NSObjectProtocol {
    associatedtype T   
    func cellFor(object: T) -> UITableViewCell    
}

这个错误出现在我定义customDelegate的地方:

Protocol 'GenericTableViewDelegate' 只能用作通用约束,因为它具有 Self 或关联的类型要求

我了解这个问题,但我不知道该怎么做。

感谢您的帮助。

【问题讨论】:

    标签: ios swift protocols swift-protocols


    【解决方案1】:

    如错误所述:

    Protocol 'GenericTableViewDelegate' 只能用作通用约束,因为它具有 Self 或关联的类型要求。

    所以,让我们这样做吧:

    class GenericTableView<Delegate: GenericTableViewDelegate>: UITableView {
        weak var customDelegate: Delegate?
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多