【问题标题】:Collectionview in tableview cell表格视图单元格中的集合视图
【发布时间】:2017-05-22 04:07:26
【问题描述】:

我现在在表格视图单元格中获取了集合视图,当我单击集合视图单元格时,它将转到下一个视图控制器,这可能吗?我已经尝试过 select item 方法,如何使用 perform segue 方法

【问题讨论】:

    标签: swift3


    【解决方案1】:

    我给你看例子

         class ViewController: UIViewController, UITableViewDelegate,
         UITableViewDataSource {
             @IBOutlet weak var tableView: UITableView!  
        override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
            return false
        }
     }
    

    这个 ViewController 包含 Tableview 数据源 n 个委托。其 DemoTableViewCell 类型的单元格如下所示

        class DemoTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
            var parentVC: UIViewController?
    
            @IBOutlet weak var collectionView: UICollectionView!
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
            return 10
        }
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
            let demoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DemoCollectionViewCell", for: indexPath) as! DemoCollectionViewCell
            return demoCollectionViewCell
        }
    
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
            (self.parentVC as! ViewController).performSegue(withIdentifier: "YourSegueName", sender: self)
    
    
        }
        }
    

    DemoTableViewCell 再次包含数据源和集合视图的委托,如上所示 didSelectItemAt 还包含 performSegue,它使用 Segue 的父引用。

    现在在集合视图单元格中,有 1 个名为 parentVC 的变量,你必须像这样在 ViewController 类中定义的 cellForRowatIndexpath 中设置这个值

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
           let demoTableViewCell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell", for: indexPath) as! DemoTableViewCell
            demoTableViewCell.parentVC = self
            demoTableViewCell.collectionView.reloadData()
            return demoTableViewCell
        }
    

    最后从情节提要上的 collectionViewCell 到 YourController 进行转场

    【讨论】:

    • 我需要在 tableview 单元格的第一部分中使用 collectionview 并且仍然没有 collectionviews ,当单击第二部分 tableview 单元格时它执行为 segue 做准备,现在我的问题是你写的应该执行是错误的,如果我们给false ,tableview 会为 segue 方法做准备吗?
    • 在这种情况下,当您单击任何表格单元格时,您需要调用 performSegue 方法,例如 self.performSegue(withIdentifier: "your_segue_identifier", sender: self) 和 shouldPerformSegue 将保持返回 false。跨度>
    • 感谢您的回答。我有一个类似的问题,我解决了它。我认为这个答案的关键部分是在 View 中设置var parentVC: UIViewController?,并通过demoTableViewCell.parentVC = selfcellForRowAt 设置该控制器。