Wayne
Wayne

Reputation: 363

Subclass UICollectionView

So, I need to extend UICollectionView functionality, override Cells, etc. In every example I see subclassing of UICollectionViewController, but not just UICollectionView.

I don't want to make my new class (called GridSet) as superclass for a single page (UIViewController) in storyboard, cause I have more elements (custom buttons, labels etc) and I don't want to maintain them in my new class, but I want to maintain them in a my page UIViewController.

I even want to insert two of my subclasses in one UIViewController and do it in storyboard (but you can't place one UIViewController inside another UIViewController.

The problem is, when I'm subclassing UICollectionView and UICollectionViewDataSource, seems like it even don't initialize.

class GridSet: UICollectionView, UICollectionViewDataSource {

let computers = [
    ["Name" : "MacBook Air", "Color" : "Silver"],
    ["Name" : "MacBook Pro", "Color" : "Silver"],
    ["Name" : "iMac", "Color" : "Silver"],
    ["Name" : "Mac Mini", "Color" : "Silver"],
    ["Name" : "Mac Pro", "Color" : "Black"]
]

override func awakeFromNib() {
    super.awakeFromNib()

    let nib = UINib(nibName: "GridSetCell", bundle: nil)
    self.registerNib(nib, forCellWithReuseIdentifier: "GridSetCellDefault")
}

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

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = self.dequeueReusableCellWithReuseIdentifier("GridSetCellDefault", forIndexPath: indexPath) as GridSetCell

    cell.label = computers[indexPath.row]["Name"]!

    return cell
}

}

I use nib for custom cell:

class GridSetCell: UICollectionViewCell {

@IBOutlet private weak var cLabel: UILabel!
@IBOutlet private weak var cBack: UIImageView!

var label: String = "" {
    didSet {
        if (label != oldValue) {
            cLabel.text = label
        }
    }
}

var back: String = "" {
    didSet {
        if (back != oldValue) {
            cBack.image = UIImage(named: back)
        }
    }
}

}

Upvotes: 1

Views: 3118

Answers (1)

SoCor
SoCor

Reputation: 803

Start by subclassing UICollectionViewCell and the UICollectionViewLayout to achieve your goals, using your versions in the system UICollectionView. This tutorial shows the steps: http://skeuo.com/uicollectionview-custom-layout-tutorial When those are working, if you still need to subclass UICollectionView, you'll have working components to install "into" that new subclass.

Upvotes: 1

Related Questions