【发布时间】:2017-12-20 03:53:01
【问题描述】:
问题:如何通过扩展编写UITableViewDataSource的默认实现?
Swift 支持协议扩展中的默认实现,UITableViewDataSource 是一个协议。那么为什么下面的例子不起作用呢?
我尝试了下面的示例,但表格保持空白。可以肯定的是,我在默认实现中添加了断点,但没有到达它们。我在里面放了print 方法,但它们什么也没打印。
此扩展将使基本表视图的使用几乎无需代码,因为它们只需要符合TableItem 的实体集合。
This question with similar title is unrelated.
完整示例:
import UIKit
/// Conform to this protocol to be immediatelly usable in table views.
protocol TableItem {
var textLabel: String? { get }
var detailTextLabel: String? { get }
}
protocol BasicTableDataSource {
associatedtype TableItemType: TableItem
var tableItems: [TableItemType]? { get set }
/// The table view will dequeue a cell with this identifier.
/// Leave empty to use `cellStyle`.
var cellIdentifier: String? { get set }
/// If `cellIdentifier` is empty, the table view will use this cell style.
/// Leave empty to use `UITableViewCellStyle.default`.
var cellStyle: UITableViewCellStyle? { get set }
}
extension UITableViewDataSource where Self: BasicTableDataSource {
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return tableItems?.count ?? 0
}
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = cellIdentifier == nil
? UITableViewCell(
style: cellStyle ?? .default,
reuseIdentifier: nil)
: tableView.dequeueReusableCell(
withIdentifier: cellIdentifier!,
for: indexPath)
let tableItem = tableItems?[indexPath.row]
cell.textLabel?.text = tableItem?.textLabel
cell.detailTextLabel?.text = tableItem?.detailTextLabel
return cell
}
}
class ProductsTableViewController: UITableViewController, BasicTableDataSource {
var cellIdentifier: String?
var cellStyle: UITableViewCellStyle? = .subtitle
/// Product conforms to TableItem
var tableItems: [Product]? = Sample.someProducts()
}
【问题讨论】:
-
您是否尝试在
viewDidLoad()中调用.reloadData()方法? -
我试过
.reloadData(),在这种情况下它什么也没做 -
你在哪里设置
dataSource?像这样的东西:self.dataSource = self -
UITableViewController设置dataSource本身,它不是UIViewController
标签: swift uitableview swift-protocols