单击特定项目时 TableView 无法检测到

TableView cannot detect when clicking on specific item

嘿,我有一个工作的 UITable,它可以从我的数组中加载项目,但现在我需要在单击 UITable 的特定项目时进行调用

我的 viewcontroller 代码下面有我自己的 class,我可以像这样创建它:

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
    }

didSelectRowAt 属于 UITableViewDelegate。如果您想在同一 class 中实现此方法,则需要采用协议

class TableDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { ...

并在 attach(to

中设置 table 视图的 delegate
func attach(to view: UITableView) {
    // Setup itself as table data source (Implementation in separated extension)
    view.dataSource = self
    view.delegate = self
    // Register element for dequeuing (All dequeuing element must register in table before)
    view.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
}