Grid layout with CollectionView in Swift

Create the UICollectionViewController like this in a file that sub-classes from UICollectionViewController:

convenience override init() {
    var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.itemSize = CGSizeMake(<width>, <height>)
    // Setting the space between cells
    layout.minimumInteritemSpacing = <Space between columns>
    layout.minimumLineSpacing = <Space between rows>
    return (self.init(collectionViewLayout: layout))
}

In the viewDidLoad you an set the background color like this:

self.collectionView.backgroundColor = UIColor.orangeColor()

My guess is you can set a background image like this:

self.collectionView?.backgroundColor = UIColor(patternImage: UIImage(named: "image.png")!)

The blur effect that you found looks good. I am having trouble figuring out how it would work though. Probably set it using the backgroundView property.

I’ll update if I find the answer.

Update:

Here is an idea of something that might work for blurring the cells.

Create a cocoa-touch class that sub-classes from UICollectionViewCell, then add this code to it:

convenience override init(frame: CGRect) {
    self.init(frame: frame)
    var blurEffect: UIVisualEffect
    blurEffect = UIBlurEffect(style: .Light)
    var visualEffectView: UIVisualEffectView
    visualEffectView = UIVisualEffectView(effect: blurEffect)
    visualEffectView.frame = self.maskView!.bounds
    self.addSubview(visualEffectView)
}

override func layoutSubviews() {
    super.layoutSubviews()
    self.maskView!.frame = self.contentView.bounds
}

Then in the CollectionViewController file, in the viewDidLoad, change this line of code:

self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

Change UICollectionViewCell.self to <Name of CollectionViewCell file>.self

Leave a Comment

tech