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

查看:60
本文介绍了问题检测按钮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.


  • 子类 UITableViewCell ,用于标识UI元素的 viewWithTag 方法已过时。

  • 将自定义单元格的类设置为子类的名称,并将标识符设置为<接口生成器中的code> 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.

添加回调 property。

Add a callback property.

添加操作并将按钮连接到操作。

Add an action and connect the button to the action.

class ButtonCell: UITableViewCell {

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

    @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.

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

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