思路简单说明
工厂模式可以简单理解成:根据接口,创建不同的对象。
在实际项目中,可能需获取Model数组, 再由tableViewCell呈现到界面给用户(CollectionView同理).我们得知道自己需要什么, 当然工厂的产品应该是不同种类的cell,。根据不同的model, 创建一个cellFactory, 放入Model, 进行处理, 生成不同的cell。
具体代码
下面贴上具体代码
2.1工厂代码:
//
// ShopCellFactory.swift
// @018使用工厂模式的TableView
//
// Created by Zack on 2017/11/15.
// Copyright © 2017年 Zack. All rights reserved.
//
import UIKit
// 可选实现协议方法
@objc protocol ShopGoodsProtocol:NSObjectProtocol {
// 也可以不可选,看需求
@objc optional var model: ShopModel { get set}
@objc optional func chooseShopGoods(cell: ShopGoodsProtocol, btn: UIButton)
@objc optional func addShopGoods(cell: ShopGoodsProtocol, btn: UIButton)
@objc optional func minusShopGoods(cell: ShopGoodsProtocol, btn: UIButton)
@objc optional func showShopInf(cell: ShopGoodsProtocol, imgV: UIImageView)
}
extension ShopGoodsProtocol {
//这里可以写一些默认实现
func showShopInf(cell: ShopGoodsProtocol, imgV: UIImageView) {
print(model?.imageName ?? "图片")
}
}
// 具体的工厂:
struct ShopFactory {
static func createCell(model: ShopModel, tableView: UITableView, indexPath: IndexPath) -> ShopGoodsProtocol? {
switch model.id {
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: model.imageName!, for: indexPath) as! NormalCell
cell.configCell(model)
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: model.imageName!, for: indexPath) as! CarryGiftCell
cell.configCell(model)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: model.imageName!, for: indexPath) as! FullGiftCell
cell.configCell(model)
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: model.imageName!, for: indexPath) as! StockoutCell
cell.configCell(model)
return cell
default:
return nil
}
}
}
备注:这里只是简单演示了下,为了方便都设为可选,而且具体cell中也没有实现。
2.2其中的一个cell:
class CarryGiftCell: UITableViewCell , ShopGoodsProtocol {
func configCell(_ model: ShopModel) {
self.textLabel?.text = model.title
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIColor.yellow
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
2.3控制器:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ShopFactory.createCell(model: self.dataArray[indexPath.row], tableView: tableView, indexPath: indexPath)
return cell as! UITableViewCell
}
效果

具体代码:
工厂模式创建不同cell
网友评论