【问题标题】:Combine Migration?合并迁移?
【发布时间】:2020-08-08 12:54:26
【问题描述】:

如何用组合框架替换当用户点击表格视图单元格的按钮时调用的闭包或委托回调?

问题 - 如果从视图控制器添加订阅者并将返回的 AnyCancellable 存储在 Set 中; 1. anyCancellable 的存储随着单元格返回 0.2 越来越高。当用户点击单元格的一个按钮时,许多订阅者都会收到价值

我使用了内置订阅者Sink

在 ViewController 中

 var myAnyCancellableSet: Set<AnyCancellable> = []

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mycell")
        cell.doSomethingSubject.sink { 
print("user tap button on cell")
                            }.store(in: &myAnyCancellableSet)
        return cell
                    }

在表格视图单元格中

import UIKit
import Combine

class MyTableViewCell: UITableViewCell {
   
    private lazy var myDoSomethingSubject = PassthroughSubject<Void, Never>()
    lazy var doSomethingSubject = myDoSomethingSubject.eraseToAnyPublisher()
    
   @IBAction func buttonTapped(_ sender: UIButton) {
        myDoSomethingSubject.send()
    }

}

【问题讨论】:

  • 不清楚(至少对我来说)你在问什么。您能否分享一些您拥有(并且想要更改)或您尝试过的代码
  • @NewDev 旧方式 - 当用户点击 tableViewcell 中的按钮时,我们使用委托模式从 viewCotroller 通知。结合- ?我需要使用 Apples Combine 框架来完成这项工作。
  • 我所说的只是代码说明问题......我建议你花时间用一些代码来编辑你的问题来说明问题
  • @NewDev 我添加了

标签: ios swift combine


【解决方案1】:

不要将所有门票放在一起。按索引路径存储。

var ticketForIndexPath: [IndexPath: AnyCancellable] = [:]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell") as! MyCell
    ticketForIndexPath[indexPath] = cell.doSomethingSubject.sink {
        print("user tap button on cell")
    }
    return cell
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    ticketForIndexPath[indexPath] = nil
}

【讨论】:

  • 除了在返回单元格时添加订阅者之外,还有什么最好的方法来处理这个问题?
  • 因为委托模式或关闭看起来很容易......除了我们无法分别完成 vale 的错误和成功。
猜你喜欢
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 2018-08-01
  • 1970-01-01
  • 2014-09-17
  • 2012-11-02
  • 1970-01-01
相关资源
最近更新 更多