如何用 Combine 框架 替换当用户点击表格 View 单元格的按钮时调用的闭包或委托(delegate)回调?
问题 - 如果从 View Controller 添加 Subscriber 并将返回的 AnyCancellable 存储在 Set 中; 1. 随着单元格返回 .2,anyCancellable 的存储越来越高。当用户点击单元格的一个按钮时,许多订阅者会收到值(value)
我使用了内置订阅者 Sink
在 View Controller 中
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
}
在表格 View 单元格中
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()
}
}
最佳答案
不要将所有门票存放在一起。通过索引路径存储它们。
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
}
关于ios - 合并迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63315649/