ios - Swft3 (RxSwift, RxCocoa) - 使用响应式(Reactive)编程的 TableView 展开和折叠概念

标签 ios swift swift3 rx-swift rx-cocoa

最近开始使用响应式(Reactive)编程在 Swift 中编写代码。响应式(Reactive)编程是一个令人困惑的概念,无论如何,我想使用响应式(Reactive)编程来实现具有扩展和折叠概念的表格 View 。我以自己的方式尝试过,我能够编写代码来实现正常、部分表格 View 和 here他们还提供了示例,但是对于展开和折叠表格 View ,我没有找到任何示例。谁能提供一下解决方案吗?

最佳答案

我假设您熟悉“combineLatest”。 这个答案并不是真正“干净”,但会以某种方式给出如何实现它的想法:

首先定义一个数组:

var expansions = [Variable<Bool>].init(repeating: Variable<Bool>(true), count: 2)

我的例子中只有 2 个部分,如果您的部分数量未知,则必须使用 [Int: Variable<Bool>]将每个部分映射到该字典中。

现在定义一个获取扩展的方法:

func expansion(for section: Int) -> Variable<Bool> {
    /* if using [Int: Variable<Bool>]
    if expansions[section] == nil {
        expansions[section = Variable<Bool>(false)
    }*/
    return expansions[section]
}

现在使用Observable.combineLatest过滤您的项目和expansion(for: _)

在 tableView 委托(delegate)中:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    // next line just dequeues a UITableViewHeaderFooterView subclass.
    let view = tableView.dequeueReusableHeaderFooter(forSection: section) as ExpandableHeader
    view.titleLabel.text = dataSource[section].model.title
    view.isExpanded = expansions[section].value // just a variable to update header's UI
    view.expandButton.rx.controlEvent(.touchUpInside)
        .bind { [weak self, weak view = view] in
            guard let strongSelf = self else { return }
            strongSelf.expansions[section].value = !strongSelf.expansions[section].value
            view?.isExpanded = strongSelf.expansions[section].value // because dataSource will not reload this view itself unless it gets dequeued.
    }
    .disposed(by: view.disposeBag)
    return view
}

通知

我正在使用 view.disposeBag 处理此订阅不是我在这个 viewController 中使用的那个。因为view.disposeBag将在 prepareForReuse() 更新每次都会删除所有以前的订阅者。 (不使用这种方法,不会导致内存泄漏,但会导致 ViewController 消耗大量资源,当然还会导致不必要的行为)

关于ios - Swft3 (RxSwift, RxCocoa) - 使用响应式(Reactive)编程的 TableView 展开和折叠概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40255597/

相关文章:

ios - 如何使用带参数和回调的 alamofire post request swift 3?

linux - Swift 3 预览版 2 Linux 错误 : use of unresolved identifier

ios - SiriKit INPayBillIntentHandling - Siri 说, "I wish I could, but <App> hasn' t 还没有和我一起设置。”

swift - 如果以编程方式加载类,则无法连接到 socket

ios - 通过 Storyboard Segue 传递对象

javascript - 修改WKWebView中不存在的DOM元素

ios - 如何在 Swift 中将 NSMutableArray 作为对 NSMutableDictionary 部分的引用传递?

ios - Swift 3.0中如何用代码控制Status Bar样式

iphone - NSXMLParser 遇到特殊字符后停止解析

ios - `CountedSet` 初始化问题