【问题标题】:How to Navigate to new View Controller from collection view cell? In Swift如何从集合视图单元导航到新的视图控制器?在斯威夫特
【发布时间】:2021-10-29 22:29:13
【问题描述】:

我有两个视图控制器(VC-1、VC-2)。 视图控制器 1 有一个表视图,并且该表视图由 4 个集合视图组成。我想导航到新的 VC(VC-2)。但无法在集合 View 的 didSelect 方法中获取“self.storyboard.instantiateViewController”。 那么现在我如何导航到 VC-2

【问题讨论】:

    标签: swift uitableview uicollectionview uinavigationcontroller storyboard


    【解决方案1】:

    您应该使用委托。您可以创建一个协议并定义一个路由方法并将其实现到VC1中

    【讨论】:

      【解决方案2】:

      您可以使用以下示例代码。 此代码使用闭包语法

      class FirstVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
          
          override func viewDidLoad() {
              super.viewDidLoad()
          }
          
          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return 5
          }
          
          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              
              let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell_Identifier") as! TableCell
              cell.configureCell(data: ["Your", "Data"])
              
              cell.didSelectRow = { data in
                  // Goto second view controller
                  let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondVC")
                  self.navigationController?.pushViewController(vc!, animated: true)
              }
              return cell
          }
      }
      
      class TableCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
          
          @IBOutlet weak var colView: UICollectionView!
          var didSelectRow: ((_ data: String) -> Void)? = nil // Closure
          
          var arrData = [String]()
          
          func configureCell(data: [String]) {
              // Setup CollectionView data
              self.arrData = data
              self.colView.reloadData()
          }
          
          func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
              return self.arrData.count
          }
          
          func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
              
              let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL_IDENTIFIER", for: indexPath)
              
              return cell
          }
          
          func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
              
              let data = self.arrData[indexPath.row]
              didSelectRow?(data)
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 2017-09-10
        • 2020-05-27
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        相关资源
        最近更新 更多