Skip to content

Instantly share code, notes, and snippets.

@rdougan
Created September 29, 2015 10:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rdougan/e54214c5f27f5807b16b to your computer and use it in GitHub Desktop.
Save rdougan/e54214c5f27f5807b16b to your computer and use it in GitHub Desktop.
A basic NSCollectionViewLayout subclass which displays NSCollectionView items in a list layout.
//
// CollectionViewListLayout.swift
// money
//
// Created by Robert Dougan on 29/09/15.
// Copyright © 2015 Phyn3t. All rights reserved.
//
import Cocoa
class CollectionViewListLayout: NSCollectionViewLayout {
var itemHeight: CGFloat = 100
var verticalSpacing: CGFloat = 0
var containerPadding: NSEdgeInsets = NSEdgeInsetsZero
override var collectionViewContentSize: NSSize {
get {
let count = self.collectionView?.numberOfItemsInSection(0)
if (count == 0) {
return NSZeroSize
}
var size = self.collectionView!.superview!.bounds.size
size.height = (CGFloat(count!) * (self.itemHeight + self.verticalSpacing)) - self.verticalSpacing + self.containerPadding.top + self.containerPadding.bottom
return size
}
}
override func prepareLayout() {
super.prepareLayout()
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> NSCollectionViewLayoutAttributes? {
let count = self.collectionView?.numberOfItemsInSection(0)
if (count == 0) {
return nil
}
let frame = NSMakeRect(self.containerPadding.left, self.containerPadding.top + ((self.itemHeight + self.verticalSpacing) * CGFloat(indexPath.item)), self.collectionViewContentSize.width - self.containerPadding.left - self.containerPadding.right, self.itemHeight)
let itemAttributes = NSCollectionViewLayoutAttributes(forItemWithIndexPath: indexPath)
itemAttributes.frame = frame
return itemAttributes
}
override func layoutAttributesForElementsInRect(rect: NSRect) -> [NSCollectionViewLayoutAttributes] {
let count = self.collectionView?.numberOfItemsInSection(0) as Int!
var attributes = [NSCollectionViewLayoutAttributes]()
for index in 0...(count - 1) {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
if let itemAttributes = self.layoutAttributesForItemAtIndexPath(indexPath) {
attributes.append(itemAttributes)
}
}
return attributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: NSRect) -> Bool {
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment