Swift中TableView内嵌CollectionView的Cell按钮初始化报错如何解决
报错原因
你定义的TableViewCellModel结构体中,colors属性的元素类型被固定为CollectionViewCellModel,但第二个分组你往数组里放入了CollectionViewCellModelButton类型的实例,两类类型不匹配,所以触发了类型转换报错。
解决方案
推荐用枚举统一两类CollectionView Cell的模型类型,操作步骤如下:
1. 定义统一的模型枚举
新增枚举类型,把两种cell的模型都封装为枚举的关联值:
enum CollectionItemModel { case dealItem(CollectionViewCellModel) case categoryButtonItem(CollectionViewCellModelButton) }
2. 修改TableViewCellModel的属性类型
把TableViewCellModel中colors属性的原类型[[CollectionViewCellModel]],修改为[[CollectionItemModel]]。
3. 调整数据源赋值
给两类不同的模型套上对应的枚举值即可解决类型不匹配报错:
struct Colors { var objectsArray = [ TableViewCellModel( category: "ALL DEALS", headerButton: UIButton.init(), colors: [ [.dealItem(CollectionViewCellModel(image: UIImage(named:"Rectangle1x.png")!, dicountAmountLabel: "30%", dicountLabel: "Discount", customerTypeLabel: "For All HBL Customers")), .dealItem(CollectionViewCellModel(image: UIImage(named:"Rectangle2.png")!, dicountAmountLabel: "30%", dicountLabel: "Discount", customerTypeLabel: "For All HBL Customers"))] ]), TableViewCellModel( category: "CATEGORIES", colors: [ [.categoryButtonItem(CollectionViewCellModelButton(collectionButton:UIButton.init())), .categoryButtonItem(CollectionViewCellModelButton(collectionButton:UIButton.init())), .categoryButtonItem(CollectionViewCellModelButton(collectionButton:UIButton.init())), .categoryButtonItem(CollectionViewCellModelButton(collectionButton:UIButton.init()))] ]) ] }
4. 适配CollectionView数据源逻辑
在返回CollectionView Cell的代理方法中,判断枚举类型对应出队不同的Cell、完成赋值:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = currentTableViewCellModel.colors[indexPath.section][indexPath.row] switch item { case .dealItem(let model): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DealCell", for: indexPath) as! CollectionViewCell // 赋值优惠类Cell的图片、文案 return cell case .categoryButtonItem(let model): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCell", for: indexPath) as! CollectionViewCellButton // 给按钮设置标题 cell.collectionButton.setTitle("分类名称", for: .normal) return cell } }
额外优化建议
不推荐在数据模型里存储UIButton这类UI控件,建议把CollectionViewCellModelButton里的UIButton属性替换成按钮标题、图标这类纯数据字段,UI控件统一在Cell层初始化,避免出现循环引用、内存泄漏问题。
内容的提问来源于stack exchange,提问作者getc
相关产品推荐
相关产品推荐

