2017-07-14 54 views
1

我目前有一个UICollectionView表与单元格,我试图让每个单元格被创建有自己独特的视图控制器。例如,当点击UICollectionViewCell时,视图控制器将显示该特定单元格。我知道我可以创建一个viewcontroller并执行segue只有一个视图控制器。这只涵盖了一个单元格...如果用户创建了25个单元格......我如何为每个单元格创建视图控制器而无需创建一个segue?下面的代码是创建一个单元格。创建新的视图控制器UICollectionViewCell点击

// MARK: Create collection View cell with title, image, and rounded border 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatCell 
    let object = objects[indexPath.row] 

    cell.chatLabel.text = object.title ?? "" 
    cell.chatImage.image = object.image 
    if let chatImagePath = object.imagePath { 
     if let imageURL = URL(string: chatImagePath) { 
     cell.chatImage.sd_setImage(with: imageURL) 
     } 
    } 
    cell.layer.borderWidth = 0.5 
    cell.layer.borderColor = UIColor.darkGray.cgColor 
    cell.layer.masksToBounds = true 
    cell.layer.cornerRadius = 8 

    return cell 
} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return objects.count 
} 

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    let itemWidth = photoCollectionView.bounds.width 
    let itemHeight = photoCollectionView.bounds.height/2 
    return CGSize(width: itemWidth, height: itemHeight) 
} 
+1

但是,您是否真的有这些目标视图控制器的25个完全不同的设计?或者他们是同一种基本类型的视图控制器,只是显示不同的数据? – Rob

+0

@Rob我想为该单元格创建一个视图控制器...我不能让所有的单元格都指向相同的视图控制器 –

+0

@Rob是他们都有相同的布局,但我想发布不同的数据在每个 –

回答

1

在您的问题下方的评论,你澄清,你真的只有你正在过渡到视图控制器的一个基本类型,但你要确保你提供正确的信息,它的您点击收集视图的哪个单元格的基础。

有两种基本方法:

  1. 最简单的,在IB,创建集合观察室在故事板的一个场景一个SEGUE,然后实现prepare(for:sender:)在始发现场通过任何你需要到下一个场景。

    例如,你可能有一个prepare(for:sender:),做一样的东西:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
        if let indexPath = collectionView?.indexPathsForSelectedItems?.first, let destination = segue.destination as? DetailsViewController { 
         destination.object = objects[indexPath.item] 
        } 
    } 
    

    现在,这使得一吨的假设(例如,我的收藏视图有一个数组,objects,我的目标视图控制器一个DetailsViewController,它有一些object财产,等等),但希望它说明了基本的想法。

  2. 你说你不想使用segue。我不知道为什么,但是,如果你真的不想继续使用,那么只需使用工具collectionView(_:didSelectItemAt:),然后以编程方式启动转换,无论你想要什么。

+0

这就是我想要做的......我试图通过单击单元格来创建一个segue,以显示该特定单元格的tableviewcontroller ... –

+0

你想看看我的github项目吗? –

+0

当然,如果它不太毛茸茸。如果有大量不相关的代码,您可能希望将其缩减为[最小,完整,可重现的示例](http://stackoverflow.com/help/mcve)。 – Rob

相关问题