Created
September 29, 2015 10:42
-
-
Save rdougan/e54214c5f27f5807b16b to your computer and use it in GitHub Desktop.
A basic NSCollectionViewLayout subclass which displays NSCollectionView items in a list layout.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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