swift - 具有默认实现的 UITableViewDataSource 扩展

标签 swift uitableview swift-protocols

问题:如何通过扩展编写 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/

相关文章:

ios - UIScrollView 禁用顶部弹跳

ios - 如何更新tableView单元格高度

ios - UITableView 滚动时崩溃(iOS 7.1.2)

c# - 从 TableView 打开 View

ios - 更改日期较早的单元格的背景颜色

swift - 当类型符合多个协议(protocol)时,为什么不满足 Swift 协议(protocol)一致性

ios - 协议(protocol)实现协议(protocol)的默认实现

ios - 当我使用自定义 UIColors 时标签的文本颜色没有改变

ios - UIBezierPath 三角形反转

swift - Swift 协议(protocol)可以是单例的吗?