在 UITableView 註冊 Cell 時,使用**唯一識別字串**對應不同顯示邏輯;dequeueReusableCellWithIdentifier: 會依識別字串回傳對應樣式的 Cell。
// 共用 Cell 類別
class MyCell: UITableViewCell {
static let idControllerA = "MyCell_ControllerA"
static let idControllerB = "MyCell_ControllerB"
// 共用 UI 元件
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
// 依 identifier 配置不同內容
func configure(for identifier: String, data: Any) {
switch identifier {
case MyCell.idControllerA:
// Controller A 風格
titleLabel.font = .boldSystemFont(ofSize: 18)
detailLabel.textColor = .gray
iconImageView.image = UIImage(named: "icon_a")
if let model = data as? ModelA { titleLabel.text = model.title }
case MyCell.idControllerB:
// Controller B 風格
titleLabel.font = .systemFont(ofSize: 16)
detailLabel.textColor = .blue
iconImageView.image = UIImage(named: "icon_b")
if let model = data as? ModelB { titleLabel.text = model.name }
default: break
}
}
}
// Controller A
class ControllerA: UIViewController, UITableViewDataSource {
let tableView = UITableView()
let dataA = [ModelA(title: "A1"), ModelA(title: "A2")]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(MyCell.self, forCellReuseIdentifier: MyCell.idControllerA)
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.idControllerA, for: indexPath) as! MyCell
cell.configure(for: MyCell.idControllerA, data: dataA[indexPath.row])
return cell
}
}
// Controller B
class ControllerB: UIViewController, UITableViewDataSource {
let tableView = UITableView()
let dataB = [ModelB(name: "B1"), ModelB(name: "B2")]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(MyCell.self, forCellReuseIdentifier: MyCell.idControllerB)
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.idControllerB, for: indexPath) as! MyCell
cell.configure(for: MyCell.idControllerB, data: dataB[indexPath.row])
return cell
}
}
MyCell_ControllerA。MyCell_A.xib、MyCell_B.xib,註冊時 tableView.register(UINib(nibName: "MyCell_A", bundle: nil), forCellReuseIdentifier: "MyCell_ControllerA")。configure 加入 case。