首页 > 解决方案 > 点击特定项目时 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...")
        }

一切正常,它显示所有项目和东西,但是当我点击一个单独的项目时,它不会打印我想要的东西。有任何想法吗 ?

标签: iosswiftuitableviewtableviewswift5

解决方案


您需要将您的委托和数据源设置为viewDidLoad.

应该是这样的:

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

推荐阅读