ios - 表格视图单元格的案例。迅速
问题描述
我有一个tableview
,我做了 cell.xib
。在这些tableview
中会有不同cell
的 s 我对 . 做同样的事情xib
。
我如何使用它的一个例子。
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell( withIdentifier: TableViewCellOne.identifier,
for: indexPath) as? TableViewCellOne
return cell ?? UITableViewCell()
}
if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell( withIdentifier: TableViewCellTwo.identifier,
for: indexPath) as? TableViewCellTWo
return cell ?? UITableViewCell()
}
return UITableViewCell()
}
但我不喜欢这种方法。我该怎么做case
?
解决方案
您可以像这样编写协议DequeueInitializable
及其扩展
protocol DequeueInitializable {
static var reuseableIdentifier: String { get }
}
extension DequeueInitializable where Self: UITableViewCell {
static var reuseableIdentifier: String {
return String(describing: Self.self)
}
static func dequeue(tableView: UITableView) -> Self {
guard let cell = tableView.dequeueReusableCell(withIdentifier: self.reuseableIdentifier) else {
return UITableViewCell() as! Self
}
return cell as! Self
}
static func register(tableView: UITableView) {
let cell = UINib(nibName: self.reuseableIdentifier, bundle: nil)
tableView.register(cell, forCellReuseIdentifier: self.reuseableIdentifier)
}
}
extension DequeueInitializable where Self: UICollectionViewCell {
static var reuseableIdentifier: String {
return String(describing: Self.self)
}
static func dequeue(collectionView: UICollectionView,indexPath: IndexPath) -> Self {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseableIdentifier, for: indexPath)
return cell as! Self
}
static func register(collectionView: UICollectionView) {
let cell = UINib(nibName: self.reuseableIdentifier, bundle: nil)
collectionView.register(cell, forCellWithReuseIdentifier: self.reuseableIdentifier)
}
}
然后使用此协议确认您的单元格
class TableViewCellOne: UITableViewCell, DequeueInitializable {
}
然后在你的cellForRow
方法中
switch (indexPath.row) {
case 0:
return TableViewCellOne.dequeue(tableView: tableView)
case 1:
return TableViewCellTwo.dequeue(tableView: tableView)
default:
return UITableViewCell()
}
推荐阅读
- browser - 某些表示形式中的 Unicode 字符问题
- sql - 一张表中的两个唯一键 SQL
- r - 在两个数据集之间匹配列表中的值
- django - Django Orm,包括像 asp.net core 这样的功能
- regex - 如何在电子表格中替换 =textjoin 范围的值
- ios - 在每个单元格都包含表格视图的表格视图中选择新单元格时,无法取消选择先前选择的单元格
- selenium - XPath 中 contains 和 equals 的区别 - selenium
- linux - 为什么 GNU 排序会在这个特定文件上挂起 10 小时以上
- javascript - 来自兄弟姐妹的数组出现了一个索引短
- arrays - 对声明感到困惑