为了账号安全,请及时绑定邮箱和手机立即绑定

问题检测按钮cellForRowAt

问题检测按钮cellForRowAt

慕虎7371278 2020-02-02 15:01:34
我需要检测是否在UITableViewController中单击了按钮override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let LikesBtn = cell.viewWithTag(7) as! UIButton}
查看完整描述

3 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

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


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

将自定义单元格的类设置为子类的名称,并ButtonCellIdentifier在Interface Builder 中将标识符设置为。


添加一个callback属性。


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


class ButtonCell: UITableViewCell {


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


    @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

  }

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


编辑


如果可以添加或删除细胞,则有一个警告。在这种情况下,通过从数据源数组获取当前索引来更新索引路径


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 = {

         let actualIndexPath = IndexPath(row: dataSourceArray.index(of: item)!, section: indexPath.section)

         print("Button pressed", actualIndexPath)  

     }

     return cell

  }

如果甚至section可以更改,那么协议/代理可能会更有效。


查看完整回答
反对 回复 2020-02-02
?
ibeautiful

TA贡献1993条经验 获得超5个赞

这是我用的:


首先初始化按钮作为Outlet和其action上的TableViewCell


class MainViewCell: UITableViewCell {


@IBOutlet weak var testButton: UIButton!


@IBAction func testBClicked(_ sender: UIButton) {


    let tag = sender.tag //with this you can get which button was clicked 


}




}

然后在您的主控制器中的cellForRow函数中,像这样初始化按钮的标签:


class MainController: UIViewController, UITableViewDelegate, UITableViewDataSource, {


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


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MainViewCell



        cell.testButton.tag = indexPath.row        


        return cell

    }


}


查看完整回答
反对 回复 2020-02-02
  • 3 回答
  • 0 关注
  • 878 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信