ios - 合并迁移?

标签 ios swift combine

如何用 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/

相关文章:

ios - 暂时禁用点击手势

android - 如何在 sencha touch 中为不同的屏幕分辨率添加图像?

ios - 为 "Any iOS Device"构建 Swift 包时找不到 SwiftUI 或 Combine 类型

ios - 如何使用 Swift 以编程方式确定最新的 iOS 版本?

ios - 像按钮操作上的 Facebook 页面

属性字符串的快速标题更改颜色保持默认蓝色

ios - Swift 自动代码生成

ios - Swift 中的 NSCoding 编码和解码 UITouchProperties

快速组合 : collect after sequence publisher not called

swift - 合并SwiftUI远程获取数据-ObjectBinding不会更新 View