UICollectionView within a UICollectionViewCell (Swift)

非 Y 不嫁゛ 提交于 2019-11-30 05:28:36

Your approach to putting a UICollectionView inside each cell looks fine, but you are most likely seeing atrocious performance because you are mishandling cell reuse. You are adding a new collection view to the cell (and actually, a new image view to every thumbnail cell) EVERY time a new reusable cell is requested. If you scroll continuously, then cells will be dequeued that already have these subviews added, so you will end up with many many subviews under each cell.

Instead, add a means of checking whether a cell already has the subview or not, and only add it if it doesn't. Probably the best way is by using a custom cell subclass:

class ThumbnailCollectionCell: UICollectionViewCell {
    var thumbnailViewController: ThumbnailCollectionViewController?
}

Back in your MainCollectionViewController:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ThumbnailCollectionCell
    if cell.thumbnailViewController == nil {
        let thumbsViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ThumbnailColllection") as! ThumbnailCollectionViewController
        self.addChildViewController(thumbsViewController)
        thumbsViewController.view.frame = cell.bounds
        cell.addSubview(thumbsViewController.view)
        thumbsViewController.didMoveToParentViewController(self)
        cell.thumbnailViewController = thumbsViewController
    }
}

And again, something similar to prevent multiple UIImageViews being added to each thumbnail cell.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!