ios - 表格视图单元格元素无法单击并获取数据
问题描述
我有一个表格视图,在里面我放置了一个主视图。在该主视图中,我放置了一个按钮。当使用时单击我的单元格按钮。我需要获取单元格标题标签。这就是我需要的。但我尝试遵循以下代码。不知道我错过了什么。它根本没有调用我的 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?()
}
在这里,该打印语句正在控制台中打印。
解决方案
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)?
}
推荐阅读
- python - 在bash和子进程上运行时python不同的输出
- python - 尝试将 DBF 转换为 CSV 时出现 Unicode 错误
- javascript - 时事通讯注册 api 的问题
- python - 如何在列表中找到对象的特定内容?
- reactjs - 在手机上运行 localhost react 应用
- java - 从 main() 方法调用非静态方法的 Java 约定
- c# - ASP.NET Core 路由 - 仅映射特定控制器
- r - 使用正则表达式过滤 R 中只有一个“/”的路径
- react-native - React Native BlurView 亮度太暗或太亮
- google-tag-manager - 增强型电子商务 (FB-EE) 标签不跟踪收入