将 UITableView 与组合数据源绑定

Wis*_*uns 2 swift combine

我想直接将 aUITableView与 @Published 属性链接,而不使用 DiffableDataSouce。

如果我让这个人

struct Person {
    let name: String
}
Run Code Online (Sandbox Code Playgroud)

并创建数据数组:

@Published
var people = [Person(name: "Kim"), Person(name: "Charles")]
Run Code Online (Sandbox Code Playgroud)

所以我想UITableView直接绑定我的,比如:

struct Person {
    let name: String
}
Run Code Online (Sandbox Code Playgroud)

但这给出了错误

Cannot convert return expression of type 'Publishers.Count<Published[Person]>.Publisher>' to return type 'Int'

Dan*_* T. 6

这里的问题是 UITableViewDataSource 是基于拉的(框架从代码中拉数据),但发布者是基于推的(它们将数据推送到某个东西。)这意味着为了使其工作,您需要一个中介器(a la中介模式。)

一种选择是引入 RxSwift/RxCocoa 和 RxCombine 项目来在合并和 RxSwift 之间进行转换,并使用已经存在的功能。对于这个问题来说,这是一个很大的问题,但也许您还有其他领域 RxCocoa 也可以简化您的代码。

对于这个问题,我认为这里有一个调解器可以工作:

@available(iOS 13.0, *)
final class ViewController: UIViewController {

    var tableView: UITableView = UITableView()
    @Published var people = [Person(name: "Kim"), Person(name: "Charles")]
    var cancellable: AnyCancellable?

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = view.bounds
        tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        view.addSubview(tableView)

        cancellable = $people.sink(receiveValue: tableView.items { tableView, indexPath, item in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = item.name
            return cell
        })

        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            self.people = [Person(name: "Mark"), Person(name: "Allison"), Person(name: "Harold")]
        }
    }
}

extension UITableView {
    func items<Element>(_ builder: @escaping (UITableView, IndexPath, Element) -> UITableViewCell) -> ([Element]) -> Void {
        let dataSource = CombineTableViewDataSource(builder: builder)
        return { items in
            dataSource.pushElements(items, to: self)
        }
    }
}

class CombineTableViewDataSource<Element>: NSObject, UITableViewDataSource {

    let build: (UITableView, IndexPath, Element) -> UITableViewCell
    var elements: [Element] = []

    init(builder: @escaping (UITableView, IndexPath, Element) -> UITableViewCell) {
        build = builder
        super.init()
    }

    func pushElements(_ elements: [Element], to tableView: UITableView) {
        tableView.dataSource = self
        self.elements = elements
        tableView.reloadData()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        elements.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        build(tableView, indexPath, elements[indexPath.row])
    }
}
Run Code Online (Sandbox Code Playgroud)