ios - 点击特定项目时 TableView 无法检测到
问题描述
嘿,我有一个工作 UITable 可以从我的数组中加载项目,但是现在我需要在单击 UITable 的特定项目时进行调用
我在 viewcontroller 的代码下面有自己的类,我可以像这样创建它:
class TableDataSource: NSObject, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "\(UITableViewCell.self)"
let item = items[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
cell.textLabel?.text = item
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("lol")
}
var items: [String] = []
func attach(to view: UITableView) {
// Setup itself as table data source (Implementation in separated extension)
view.dataSource = self
// Register element for dequeuing (All dequeuing element must register in table before)
view.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
}
}
如您所见,我有一个 didSelectRowAt ,它应该只打印“lol”作为测试,但这不起作用
为了初始化这个 UITable 我确实这样称呼它
@IBOutlet weak var TableItemsView: UITableView!
private let dataSource = TableDataSource()
var nutList = ["empty"]
我从 firebase 调用我的数组并将其应用于 nutList:
if let document = document, document.exists {
self.nutList = document.get("nutList") as! [String]
self.dataSource.attach(to: self.TableItemsView)
self.dataSource.items = self.nutList
} else {
print("No food...")
}
一切正常,它显示所有项目和东西,但是当我点击一个单独的项目时,它不会打印我想要的东西。有任何想法吗 ?
解决方案
您需要将您的委托和数据源设置为viewDidLoad
.
应该是这样的:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
推荐阅读
- firebase - 与原生 Cloud Run 相比,使用 Firebase 托管的延迟较高
- javascript - 如何在 map 函数中使用 async 和 await 进行顺序执行
- node.js - 我该如何解决这个错误?" 抛出新的 mongoose.Error.MissingSchemaError(name);?
- objective-c - iOS13 中 Method Swizzling 的 UISceneDelegate?
- javascript - 如何在javascript中同时获取所有元素ID?
- bash - 如何将此字符串转换为 Bash 中 Python 文件的可交互列表?
- angular - ngFor中带有角度7的动态主题标签并获得价值
- php - 如何在 LARAVEL 中隐藏 URL 变量
- c++ - 私有静态成员函数与私有成员函数
- authentication - 如何为单个 Exchange Online 邮箱启用 User.Read.All?