Brian Coleman

  • Home
  • ABOUT
  • SERVICES
  • PORTFOLIO
  • BLOG
  • Contact

Tutorial: Collection View using Swift

Flow Layout
One of the best features for developers that came in the iOS 6 SDK is UICollectionView. It’s been a popular tool for developers since, so let’s review how to create one in Swift (if you need it in objective-c read Tutorial: Collection View using Flow Layout).

UICollectionView is very similar to UITableView but you can customize it a lot more and it can scroll horizontal, goodbye scroll views! Most recently I used a collection view for a bottom navigation scroller and it worked really well.

A UICollectionView view has three main components:
1. Cells: Display your content in cells that are de-queued as they leave the screen.
2. Supplementary Views: Add labels, section headers and footers to define your content areas.
3. Decoration Views: Decorate the collection view to look like a bookshelf or a background image.

Start by adding the delegates to your class file and define your collection view.

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    @IBOutlet var collectionView: UICollectionView?

The most common layout for a UICollectionView is UICollectionViewFlowLayout. Flow layout organizes items into a grid with optional header and footer views for each section. The items in the collection view flow from one row or column (depending on the scrolling direction) to the next, with each row comprising as many cells as will fit. Cells can be the same sizes or different sizes.

Define the UICollectionView & UICollectionViewFlowLayout properties in the viewDidLoad method.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 90, height: 90)
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
    collectionView!.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(collectionView!)
}

Most of the properties are self explanatory but the key is to define your cell class if you are using custom cells (just like table views) and setting the size of the cells, above they are set to 90×90. Choose your section insets which is the spacing in between each cell, I have it set to 20 for the top and 10 for the rest. Lastly define the layout, we’re using let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout().

flow_section_insets_2x

Setting up a UICollectionView is very similar to a UITableView, so you’ll recognized a lot of the methods below.

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 20
}

Above we’re defining how many items and sections are in the collection view. If you have more than one section, then you’ll need to define the number of sections, if you only have one you don’t need that method.

Below is the real meat of the UICollectionView, defining the cells with your data. If you choose to use a custom cell you can add images or whatever you need to display.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell
    cell.backgroundColor = UIColor.blackColor()
    cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
    cell.imageView?.image = UIImage(named: "circle")
    return cell
}

Collection View Data
Finally you can drag the UICollectionView object into your view within your NIB or storyboard. Move and scale the collection view to where you want to display it and review all of the properties within the inspector. Be sure to hookup the collectionView reference outlet and dataSource and delegates so the collection view can provide all the functionality available. Do the same for the Collection View Flow Layout. (See image on the right).

You can grab the full source code for this tutorial. Note: Built for XCode6-Beta7.
If you need it built using Xcode 6.3 (Swift 1.2).

Screen Shot 2014-09-04 at 11.12.51 AM

Tutorial: Force Upgrade in SwiftTutorial: How to use Auto Layout in Xcode 6
Brian Coleman

Manager, Mobile Development at Rogers Communications with over 15 years of multifaceted experience including development, design, business analysis and project management working directly with clients in a consulting capacity throughout the full software life cycle.

September 4, 2014 Swift, Tutorialsios8, swift, tutorial
Follow Me
    
Categories
  • About Me
  • Frameworks
  • My Apps
  • News
  • Strategy
  • Swift
  • Tools
  • Tutorials
  • tvOS
  • Uncategorized
  • Videos
  • Watch
Archives
  • May 2016
  • January 2016
  • October 2015
  • July 2015
  • May 2015
  • April 2015
  • March 2015
  • November 2014
  • October 2014
  • September 2014
  • July 2014
  • June 2014
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
Recent Posts
  • Classix for iPhone, iPad & Apple TV
  • Tutorial: How to test your app for IPv6 compatibility
  • Tutorial: Testing SSL using Charles Proxy on an iOS Device
  • Tutorial: 3D Touch – Quick Actions in Swift
  • tvOS Tutorial: Top Shelf in Swift
Featured Apps
Classix
Sportsnet
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
Search
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
ABOUT
Brian is a Lead iOS/tvOS Developer from Toronto with over 18 years of multifaceted experience including development, design, business analysis and project management.

FOLLOW ME
    
Email Subscription
Sign up for my newsletter to receive the latest news and tutorials posted.

Enter your email address:

2023 © Brian Coleman