如何在Swift 5中从UITableView单击按钮获取索引路径 [英] How to get index path on click of button from UITableView in Swift 5

查看:103
本文介绍了如何在Swift 5中从UITableView单击按钮获取索引路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在tableview中,单元格中有按钮,需要获取tableview的索引,单击该索引单元格的按钮.因此,无法迅速实现它.到目前为止,已经尝试过了,但这给了我错误的价值.

In tableview, on the cells there are buttons in it, need to get the index of tableview means, which index cell's button is clicked. So, not able to implement it in swift 5. So far tried is but this give me wrong value.

let position: CGPoint = sender.convert(CGPoint.zero, to: organizationsTableView)
if let indexPath = organizationsTableView.indexPathForRow(at: position) {
    print(indexPath)
}

推荐答案

1)在自定义"单元格中添加闭包:

1) In your Custom cell add closure:

class YoutuberTableViewCell: UITableViewCell {

    var buttonAction : (() -> ())?


    @IBAction func buttonTapped(_ sender: UIButton) {

        buttonAction?()
    }

}

2)在您的cellForRowAt中实现闭包

2) In your cellForRowAt implement the closure

extension ViewController : UITableViewDataSource {

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

        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! YoutuberTableViewCell

        cell.buttonAction = { [unowned self] in
            let selectedIndexPath = indexPath.row
        }

        return cell
    }

}

这篇关于如何在Swift 5中从UITableView单击按钮获取索引路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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