swift - 在单元格中正确使用回调

标签 swift uitableview

我通常更喜欢使用回调,在这个例子中我想知道我是否做对了一切

我有一个带有自定义单元格的 tableView,它有 2 个按钮。

所以我有 2 个回调( block ),当用户点击按钮时我触发它们

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
    cell.firstButtonAction = {
        print(indexPath,cell)
        print(self)
    }
    cell.secondButtonAction {
        print(indexPath,cell) 
        print(self)
    }
    return cell
}

所以我的问题是,默认情况下,回调保留值的强引用,我应该使用吗

[weak self]

避免强引用循环?

同样适用于

indexPath,cell

如果细胞是可重复使用的,那么在这里捕获它们是否正确?

最佳答案

  1. 是的,如果要在闭包中使用 self,请将 [weak self][unowned self] 添加到避免保留循环。

    cell.firstButtonAction = { [weak self] in
    
  2. 不会,捕获的本地值(例如 indexPathcell)不会导致保留周期。

关于swift - 在单元格中正确使用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49243115/

相关文章:

ios - Swift 2 中的本地化

ios - Swift版本嵌入外部Framework

ios - UITableView 在 ios 中使用自定义表格单元格滚动不流畅

iphone - 使用 iPhone 上的菜单复制 Android ViewPager 类型功能

ios - UITableView 奇怪的分隔线颜色

swift - 一个 View Controller 中的两个 TableView ,swift

ios - UITableView 的 deselectRowAtIndexPath 防止 cell 的 subview 改变背景颜色

ios - Xcode:TableView 单元格创建 ViewController

xcode - 我可以将我的项目代码导入到 Swift REPL 中吗?

swift - 获取 JSON,将其解析为数组,然后在 Swift 中打印