Ios 如何为UITableVIewCell?;创建通用模型;
我有一个自定义的UITableViewCell。它将被多个TableView使用。因此它得到一个不同的模型。 我可以创建泛型模型吗?。就像Ios 如何为UITableVIewCell?;创建通用模型;,ios,swift,uitableview,generics,Ios,Swift,Uitableview,Generics,我有一个自定义的UITableViewCell。它将被多个TableView使用。因此它得到一个不同的模型。 我可以创建泛型模型吗?。就像 MODProductListCell<T>: UITableViewCell { var molde: T? } MODProductListCell:UITableViewCell{ 莫尔德:T? } 但是当我用这个手机的时候。它崩溃了。我不知道发生了什么事 guard let cell = tableView.dequeueR
MODProductListCell<T>: UITableViewCell {
var molde: T?
}
MODProductListCell:UITableViewCell{
莫尔德:T?
}
但是当我用这个手机的时候。它崩溃了。我不知道发生了什么事
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MODProductListCell", for: indexPath) as? MODProductListCell<Any> else {fatalError()}
guard let cell=tableView.dequeueReusableCell(标识符为:“MODProductListCell”,for:indexath)作为?MODProductListCell不要使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
}
}
为什么您要使用MODProductListCell将您的问题以a的形式包含所有相关代码,以使其成为主题。您是否使用故事板/XIB?如果是,您需要包括故事板/xib设置的屏幕截图。通用T
和Any
不相关。泛型不是协变的。@DávidPászor,因为会出现错误:“在转换为'MODProductListCell'时无法推断泛型参数'T'”T
不是具体类型,这是泛型类型参数。您需要设置具体类型。如果不知道或每个单元格都在更改,因此无法从情节提要中设置,那么您需要删除通用实现。@DávidPásztor谢谢。我将尝试使用协议创建模型。谢谢。你的回答给了我另一种思考方式