问题检测按钮cellForRowAt

我需要检测是否在UITableViewController中单击了按钮


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


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


}


慕虎7371278
浏览 888回答 3
3回答

慕仙森

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可以更改,那么协议/代理可能会更有效。

ibeautiful

这是我用的:首先初始化按钮作为Outlet和其action上的TableViewCellclass 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    }}
打开App,查看更多内容
随时随地看视频慕课网APP