触摸时使用UIButton检索UITableView单元格的IndexPath

时间:2018-01-15 18:23:25

标签: swift uibutton tableview

当点击单元格中的按钮时,我正在努力检索如何检索UITableViewCell的indexPath。我正在使用按钮的典型委托代码。我用Google搜索并试验了这个,但我无法得到它。这是我的Custom Tableview单元代码:

import UIKit

protocol MainTableViewCellDelegate {
    func tappedReport(id: String)
}

class MainTableViewCell: UITableViewCell {

    @IBOutlet weak var cellView: UIView!
    @IBOutlet weak var userLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var postLabel: UILabel!

    var postItem: PostData!
    var delegate: MainTableViewCellDelegate?

    func setPost(post: PostData) {
        postItem = post
        let ourPost = postItem.postId
        print(ourPost)
    }

    @IBAction func reportButton(_ sender: UIButton) {
        delegate?.tappedReport(id: postItem.postId)
        //print("Reported post ID: \(postItem.postId)")
    }
}

// View controller/ cellforRowat


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MainTableViewCell
        cell.postLabel.text = posts[indexPath.row].message
        cell.textLabel?.adjustsFontSizeToFitWidth = true
        cell.layer.cornerRadius = 8
        cell.userLabel.text = posts[indexPath.row].username

        cell.delegate = self
        cell.getIndexPath()
}

extension ViewController: MainTableViewCellDelegate {
    func tappedReport(id: String) {

        print("Hi")
        AlertController.showAlert(inViewController: self, title: "Report", message: "Report button tapped.")
    }
}

和想法?

3 个答案:

答案 0 :(得分:1)

如果您将单元格作为委托调用的一部分传回,则可以向表视图询问其索引路径。

定义委托协议:

protocol MainTableViewCellDelegate: class {
    func cell(_ cell: MainTableViewCell, didTapReport reportID: String)
}

在您的单元格中,为要点击的报告按钮定义处理程序并通知代理:

@IBAction func reportButton(_ sender: UIButton) {
    delegate?.cell(self, didTapReport: postItem.postID)
}

然后在视图控制器中(根据您的代码是您的单元格委托):

func cell(_ cell: MainTableViewCell, didTapReport reportID: String) {
    let indexPath = tableView.indexPath(for: cell)
    // Do something with the index path
}

因为可能没有该单元格的索引路径(您可以将任何单元格传递到该参数),所以返回类型是可选的,因此您必须检查indexPath是否为nil在使用它之前。所以你可能需要做一些像

这样的事情

guard let indexPath = tableView.indexPath(for: cell) else { return }

答案 1 :(得分:1)

在UITableViewCell子类中还有一个不使用委托或IB操作的选项。您可以将此方法添加为UIView扩展

extension UIView {

    func superview<T: UIView>(of viewType: T.Type) -> T? {
        if superview == nil {
            return nil
        }

        if let view = superview as? T {
            return view
        }

        return superview?.superview(of: viewType)
    }
}

并在这样的视图控制器中使用它

@IBAction func actionTapButton(_ sender: UIButton) {
    guard
        let cell = sender.superview(of: YourCustomCell.self),
        let row = tableView.indexPath(for: cell)?.row
    else {
        return
    }

    //...
}

答案 2 :(得分:0)

你可以在你的单元格内创建indexpath的属性,并在cellForRow方法中设置单元格的索引路径。

比按钮点击只需使用self.indexPath。

可能会解决您的问题