【问题标题】:How can I create general model for UITableVIewCell ?如何为 UITableVIewCell 创建通用模型?
【发布时间】:2020-07-15 09:36:39
【问题描述】:

我有一个自定义的 UITableViewCell。它将被多个 Tableviews 使用。所以它有一个不同的模型。 我可以创建一个泛型模型吗?就像

MODProductListCell<T>: UITableViewCell { 
    var molde: T? 
}

但是当我使用这个单元格时。它崩溃了。我不知道发生了什么。

guard let cell = tableView.dequeueReusableCell(withIdentifier: "MODProductListCell", for: indexPath) as? MODProductListCell<Any> else {fatalError()}

它崩溃了

所以问题是我是否有其他方法来创建通用模型,或者我现在正在做的事情有什么问题。

编辑: 我的单元格是用 XIB 创建的,看起来像:

【问题讨论】:

  • 你为什么使用MODProductListCell&lt;Any&gt;?使用您在情节提要中设置的实际类型。您还需要edit 您的问题以minimal reproducible example 的形式包含所有相关代码以使其成为主题。你在使用故事板/xibs吗?如果是,您需要包含您的故事板/xib 设置的屏幕截图。
  • 通用 TAny 不相关。泛型不是协变的。
  • @DávidPásztor 因为会有错误:“无法推断通用参数'T'强制转换为'MODProductListCell”
  • T 不是具体类型,而是泛型类型参数。您需要设置具体类型。如果这是未知的或每个单元格都在更改,因此无法从情节提要中设置,那么您需要删除通用实现。
  • @DávidPásztor 谢谢。我会尝试使用协议来创建模型。

标签: ios swift uitableview generics


【解决方案1】:

不要让UItableViewCell 通用,而是让你的模型遵循协议。所有模型想在UItableViewCell中显示数据都需要遵循一个通用的协议

//Resource protocol is used to display for cell used in table view cell

protocol ResourceProtocol {
    func snippet()
    func title()
    func image()
    func url()
}

//Model1
class ArtistResource: ResourceProtocol {
    func snippet() {
        //return snippet
    }
    
    func title() {
        //return title
    }
    
    func image() {
        //return image
    }
    
    func url() {
        //return url
    }
}

//Model2
class SongResource: ResourceProtocol {
    func snippet() {
        //return snippet
    }
    
    func title() {
        //return title
    }
    
    func image() {
        //return image
    }
    
    func url() {
        //return url
    }
}

//Model3
class AlbumResource: ResourceProtocol {
    func snippet() {
        //return snippet
    }
    
    func title() {
        //return title
    }
    
    func image() {
        //return image
    }
    
    func url() {
        //return url
    }
}

class TableViewCellView {
    var resource: ResourceProtocol
    
    init(source: ResourceProtocol) {
        resource = source
    }
    
    func loadCell() {
        //show snippet
        //show title
        //show url
        //show image
    }   
}

【讨论】:

  • 谢谢。你的回答让我有了另一种思考方式
猜你喜欢
  • 2016-10-28
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2021-09-25
相关资源
最近更新 更多