问题检测按钮 cellForRowAt [英] Issue Detecting Button cellForRowAt

查看:18
本文介绍了问题检测按钮 cellForRowAt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to detect if the button has been clicked in the UITableViewController

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

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

}

推荐答案

Swift 中最简单有效的方法是回调闭包.

The easiest and most efficient way in Swift is a callback closure.

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

  • Subclass UITableViewCell, the viewWithTag way to identify UI elements is outdated.
  • Set the class of the custom cell to the name of the subclass and set the identifier to ButtonCellIdentifier in Interface Builder.

添加一个 callback 属性.

添加一个动作并将按钮连接到该动作.

Add an action and connect the button to the action.

class ButtonCell: UITableViewCell {

    var callback : (() -> Void)?

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

  • cellForRow 中将回调分配给自定义单元格.

  • In cellForRow assign the callback to the custom cell.

    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
      }
    

  • 当按钮被按下时,回调被调用.索引路径被捕获.

  • When the button is pressed the callback is called. The index path is captured.

    编辑

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

    There is a caveat if cells can be added or removed. In this case pass the UITableViewCell instance as parameter and get the index path from there

    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
      }
    

    如果连section都可以改变,那么协议/委托可能会更有效率.

    If even the section can change, well, then protocol/delegate may be more efficient.

    这篇关于问题检测按钮 cellForRowAt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆