简体   繁体   English

使用通用参数将UITableViewCell出队

[英]Dequeue UITableViewCell with a generic parameter

Let's say we have a generic UITableViewCell : 假设我们有一个通用的UITableViewCell

class ControlTableViewCell<ControlType: UIControl>: UITableViewCell

Because when we need to create the cell we need to know the control type, we should disable this initializer: 因为当我们需要创建单元格时,我们需要知道控件的类型,所以我们应该禁用此初始化程序:

@available(*, unavailable)
    override convenience init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        fatalError("Use init().")
    }

and only use the following initializer: 并且仅使用以下初始化程序:

init(with control: ControlType, reuseIdentifier: String? = nil) {
        self.control = control
        super.init(style: .default, reuseIdentifier: reuseIdentifier)
        configureForControl()
    }

If I create a class that I want to use: 如果我创建要使用的类:

class DogTableViewCell: ControlTableViewCell<UIButton>

how would I go about dequeuing the reusable cells? 我将如何使可重复使用的单元出队? I would register first: 我先注册:

tableView.register(DogTableViewCell.cellClass,
                   forCellReuseIdentifier: DogTableViewCell.cellReuseIdentifier)

And then in the cellForRowAt : 然后在cellForRowAt

let cell = tableView.dequeueReusableCell(withIdentifier: DogTableViewCell.cellReuseIdentifier,
                                         for: indexPath) as? DogTableViewCell ?? DogTableViewCell()

But because dequeueReusableCell uses init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) we would crash at fatalError("Use init().") 但是因为dequeueReusableCell使用init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)我们将在fatalError("Use init().")处崩溃fatalError("Use init().")

Is there a good way to deal with this situation? 有解决这种情况的好方法吗? I found a number of posts that ask the same question, but they all seem to want to set some properties that can be set later on, so no point in trying to use a custom initializer when dequeueing.. but in my case the class being generic, it needs to be initialized with a type. 我发现有很多帖子问同样的问题,但是他们似乎都想设置一些以后可以设置的属性,因此在出队时尝试使用自定义的初始化方法毫无意义。但是在我的情况下,该类是泛型,需要使用类型进行初始化。

Thanks for your help. 谢谢你的帮助。

Similar posts: UITableViewCell dequeueReusableCellWithIdentifier with custom initializer 类似文章: 具有自定义初始化程序的UITableViewCell dequeueReusableCellWithIdentifier

You should remove all your initializers and add call configure method after the cell is created. 创建单元后,应删除所有初始化程序并添加调用配置方法。 For example, 例如,

func setControl(control: ControlType) {
    self.control = control
    configureForControl()
}

Call this methods after dequeueReusableCell dequeueReusableCell之后调用此方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM