问题:如何通过扩展编写 UITableViewDataSource
的默认实现?
Swift支持协议(protocol)扩展中的默认实现,UITableViewDataSource
是一个协议(protocol)。那么为什么下面的示例不起作用?
我尝试了下面的例子,但表格仍然是空白的。可以肯定的是,我在默认实现中添加了断点,但它们没有到达。我将 print
方法放入其中,但它们什么也不打印。
此扩展几乎无需代码即可使用基本 TableView ,因为它们只需要一组符合 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()
}
最佳答案
替换
extension UITableViewDataSource where Self: BasicTableDataSource
与
扩展 UITableViewDataSource
因为 UITableViewDataSource
没有确认 BasicTableDataSource
协议(protocol)。所以它不会扩展 UITableViewDataSource
More about Protocol Constraints阅读有关向协议(protocol)扩展添加约束的信息。
关于swift - 具有默认实现的 UITableViewDataSource 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47898541/