gpt4 book ai didi

ios - 问题检测按钮 cellForRowAt

转载 作者:可可西里 更新时间:2023-10-31 23:58:32 24 4
gpt4 key购买 nike

我需要检测 UITableViewController 中的按钮是否被点击

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let LikesBtn = cell.viewWithTag(7) as! UIButton

}

最佳答案

在 Swift 中最简单和最有效的方法是回调闭包。

  • 子类 UITableViewCellviewWithTag 识别 UI 元素的方式已经过时。
  • 在 Interface Builder 中将自定义单元格的类设置为子类的名称,并将标识符设置为 ButtonCellIdentifier

  • 添加一个回调属性。

  • 添加一个 Action 并将按钮连接到该 Action 。

    class ButtonCell: UITableViewCell {

    var callback : (() -> Void)?

    @IBAction func buttonPressed(_ sender : UIButton) {
    callback?()
    }
    }
  • cellForRow 中将回调分配给自定义单元格。

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellIdentifier", for: indexPath) as! ButtonCell
    cell.callback = {
    print("Button pressed", indexPath)
    }
    return cell
    }
  • 按下按钮时调用回调。捕获索引路径。

编辑

如果可以添加或删除单元格,则需要注意。在这种情况下,将 UITableViewCell 实例作为参数传递并从那里获取索引路径

class ButtonCell: UITableViewCell {

var callback : ((UITableViewCell) -> Void)?

@IBAction func buttonPressed(_ sender : UIButton) {
callback?(self)
}
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellIdentifier", for: indexPath) as! ButtonCell
let item = dataSourceArray[indexPath.row]
// do something with item
cell.callback = { cell in
let actualIndexPath = tableView.indexPath(for: cell)!
print("Button pressed", actualIndexPath)
}
return cell
}

如果连 部分 都可以改变,那么协议(protocol)/委托(delegate)可能会更有效率。

关于ios - 问题检测按钮 cellForRowAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com