iOS (Swift): UICollectionView for a given UICollectionViewCell

uicollectionview grid layout swift 4
uicollectionview swift 4 programmatically
uicollectionview swift 5
uicollectionview custom layout swift 4
uicollectionview image gallery swift
uicollectionview section header programmatically swift 4
swift uicollectionview programmatically
uicollectionview waterfall layout swift 4

I have a UICollectionViewCell subclass that is contained within a UICollectionView as follows:

class MyCell: UICollectionViewCell {

class MyViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet public var collectionView: UICollectionView!

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else { fatalError("Unexpected indexPath") }
        return cell


Is there any way to access the collectionView instance defined in MyViewController from within MyCell?

Thanks for any help.

Try something like below

protocol MyCellDelegate {
    func reloadData()
class MyCell: UICollectionViewCell {
    var delegate: MyCellDelegate!

class MyViewController: UIViewController {
    //lets say this is your view controller and datasource

extension MyViewController: UICollectionViewDataSource {
    //Methods are not implemeted here
    //But you can set the delegate of the cell in cellForRowAtIndex method which is your view controller

extension MyViewController: MyCellDelegate {
   func reloadData() {
        //Here you reload the collection view

UICollectionView Tutorial: Getting Started, In this tutorial, you'll get hands-on experience with UICollectionView by UICollectionViewCell : This is similar to a UITableViewCell in a table view. This property is specific to UICollectionViewFlowLayout and defaults to Vertical. error) : // 2 print("Error Searching: \(error)") case .results(let results): // 3  Choose File New File and choose iOS Source Cocoa Touch Class template. Click Next. Name the new class FlickrPhotoCell, making it a subclass of UICollectionViewCell. Open Main.storyboard and select the cell. In the Identity inspector, set the cell’s class to FlickrPhotoCell:

Following suggestions in the comments:

extension UICollectionViewCell {

    /// The collection view that presents this cell.
    weak var collectionView: UICollectionView! {
        return self.superview as! UICollectionView

UICollectionView Tutorial: Reusable Views, Selection and Reordering, In this tutorial, you'll level up your UICollectionView skills, learning how to This class is similar to UICollectionViewCell , except it usually displays headers and footers. method which tells the collection view if it should select a specific cell: 5 switch result { // 6 case .results(let photo): if indexPath == self. ios,unity3d,shader,mesh,particle How to draw each a vertex of a mesh as a circle? animating a view on top of uitableview ios,swift,autolayout I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items.

You can try

 class MyCell: UICollectionViewCell, UICollectionViewDataSource {

    weak var outerCollectionView: UICollectionView!

and set it in cellForRowAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else { fatalError("Unexpected indexPath") }
    cell.outerCollectionView = collectionView
    return cell


Or you can try to cast the superView like this

let collectionView = self.superView as! UICollectionView

Programmatic Custom CollectionView Cell Subclass in Swift 5 , Patience, you will be an iOS master in no time if you keep up the hard work. Add the following code to ViewController.swift and you will be given  ios,xcode,swift,uigesturerecognizer You can get a reference to the view the gesture is added to via its view property. In this case you are adding it to the button so the view property would return you you the button. let button = sender.view as?

Customizing Collection View Layouts, MosaicLayout — A UICollectionViewLayout subclass that lays out cells in a mosaic-style, nonconforming grid. See “For a Complex Grid, Define Cell Sizes  iOS | CollectionView with XCode IDE Introduction, History and Versions, Views and View Controllers, Creating the first iOS application, Label, Button, TextField, Switch, Segmented Control, iOS UI Controls, iOS UI Views, iOS UIView Controllers, Tab Bar Interface etc.

UICollectionView, Swift; Objective-C Data in the collection view is organized into individual items, which can then be grouped a cell, which is an instance of the UICollectionViewCell class that your data source configures and provides. This property controls the specified number of prototype cells for you to configure in your storyboard. Ultimate UICollectionView guide with iOS examples written in Swift. Learn how to use UICollectionView, with highly reusable UIKit components and some MVVM pattern without the going nuts with index path calculations.

Animating Items in a UICollectionView – RPLabs – Rightpoint Labs, Cells are instances of a subclass of UICollectionViewCell. The layout determines which items are visible in a given bounding rectangle within the Bear in mind the scenarios outlined above for which an item may “appear” or “​disappear”. Swift it should be animated appropriately (flown in to the right from off-screen):. ios,swift I think your problem is that you are using a calendar with an unset time zone. Your calculation of adding 60*60*24*2 to the current time does not account for the two days when some timezones change to and from daylight savings time.

  • Just use delegate and @protocol.
  • @user3344236 Thank you -- so there is no built-in method or variable that gives this information from within UICollectionViewCell?
  • What is the reason for making a collection view cell as collection view data source? I think its really a bad idea.
  • @AkshaysinghYaduvanshi Yes this was a typo -- fixed now. I still want access to the collectionView instance from MyCell, however.
  • @Alex What is the reason for doing that? I am just asking to see if i can provide a better solution for doing the same.
  • no need for as? if you're 100% crashes will guide you
  • @Sh_Khan Does this not crash with a fatal error though if somehow a UICollectionViewCell has not been placed within a UICollectionView? Do you recommend forcing the downcast using: return self.superview as! UICollectionView
  • a cellection cell can only be a subview for a UICollectionView no other options
  • Thanks for your response. I don't think MyCell wants the UICollectionViewDataSource but rather MyViewController should have that.
  • you can try self.superView
  • Definitely make that a weak property, or you’re causing a retain cycle.
  • @ABeard89 does the answer below as an extension make sense?
  • If you absolutely need to do this, I think this answer is the better option, since Apple could change the view hierarchy on a whim. That being said, there isn’t a standard way to do this because it’s bad form. I would advise against this sort of thing and employ a delegate pattern instead—the cell shouldn’t need to reference the collection view.