首页 > 解决方案 > 表格视图单元格元素无法单击并获取数据

问题描述

我有一个表格视图,在里面我放置了一个主视图。在该主视图中,我放置了一个按钮。当使用时单击我的单元格按钮。我需要获取单元格标题标签。这就是我需要的。但我尝试遵循以下代码。不知道我错过了什么。它根本没有调用我的 cell.add 目标行。

索引行的单元格中的代码:

cell.cellBtn.tag = indexPath.row
cell.cellBtn.addTarget(self, action:#selector(self.buttonPressed(_:)), for:.touchUpInside)

@objc func buttonPressed(_ sender: AnyObject) {
    print("cell tap")
    let button = sender as? UIButton
    let cell = button?.superview?.superview as? UITableViewCell
    let indexPath = tableView.indexPath(for: cell!)
    let currentCell = tableView.cellForRow(at: indexPath!)! as! KMTrainingTableViewCell
    print(indexPath?.row)
    print(currentCell.cellTitleLabel.text)
}

我什至添加了一个断点,但仍然没有调用我的 cell.addTarget 行

也尝试过关闭。在索引行的单元格中:

cell.tapCallback = {
    print(indexPath.row)
}

在我的表格视图单元格中:

var tapCallback: (() -> Void)?
@IBAction func CellBtndidTap(_ sender: Any) {
    print("Right button is tapped")
    tapCallback?() 
}

在这里,该打印语句正在控制台中打印。

标签: iosswiftuitableview

解决方案


import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var list = [String]()
    @IBOutlet weak var tableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
        cell.saveButton.tag = indexPath.row
        //cell.saveButton.accessibilityIdentifier = "some unique identifier"
        cell.tapCallback = { tag in
            print(tag)
        }
        return cell
    }
}

class MyTableViewCell: UITableViewCell {
    // MARK: - IBOutlets
    @IBOutlet weak var saveButton: UIButton!

    // MARK: - IBActions
    @IBAction func saveTapped(_ sender: UIButton) {
        tapCallback?(sender.tag)
    }

    // MARK: - Actions
    var tapCallback: ((Int) -> Void)?
}

推荐阅读