首页 > 解决方案 > 如何导航到自定义单元格中的新页面?

问题描述

我有一个自定义单元 FeedCell.swift 和控制器 FeedViewController.swift。我在每个单元格中设置了一个 btn,以便我可以导航到 detailController.swift。但是在自定义单元格中我不能使用 self.navigation。我应该怎么办?

标签: swiftuitableviewcustom-cell

解决方案


您可以在单元格中设置按钮的出口并添加目标,如下所示:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! yourCell
        cell.yourButton.addTarget(self, action: #selector(goDetail), for: .touchUpInside)
        return cell
    }

    @objc func goDetail(){
        let vc = // Declare your viewController
        self.navigationController?.pushViewController(vc, animated:true)
    }

顺便说一句,您可以在选择单元格而不是使用按钮时添加此操作

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
 let vc = // Declare your viewController
 self.navigationController?.pushViewController(vc, animated:true)
}

如果您想发送单击了哪个单元格的按钮,只需添加cell.yourButton.tag = indexPath.rowcellForRowAt修改goDetail

 @objc func goDetail(sender : UIButton){ 
     sender.tag // while give your selected cell index
    }

推荐阅读