I can't get scrolling both vertically and horizontally to work with a custom layout for NSCollectionView
.
According to the docs, in my subclass I return the collectionViewContentSize
and if that is too big, scrolling is automatically enabled in the enclosing scroll view of the collection view. However, even if I order all elements in a horizontal row, only vertical scrolling is enabled.
Here is my layout code:
class Layout: NSCollectionViewLayout
{
var cellSize = CGSize(width: 100, height: 30)
var cellSpacing: CGFloat = 10
var sectionSpacing: CGFloat = 20
private var contentSize = CGSize.zero
private var layoutAttributes = [NSIndexPath: NSCollectionViewLayoutAttributes]()
override func prepareLayout() {
guard let collectionView = collectionView else { return }
let sections = collectionView.numberOfSections
guard sections > 0 else { return }
contentSize.height = cellSize.height
for section in 0..<sections {
let items = collectionView.numberOfItemsInSection(section)
guard items > 0 else { break }
for item in 0..<items {
let origin = CGPoint(x: contentSize.width, y: 0)
let indexPath = NSIndexPath(forItem: item, inSection: section)
let attributes = NSCollectionViewLayoutAttributes(forItemWithIndexPath: indexPath)
attributes.frame = CGRect(origin: origin, size: cellSize)
layoutAttributes[indexPath] = attributes
contentSize.width += cellSize.width + cellSpacing
}
contentSize.width += sectionSpacing
}
}
override var collectionViewContentSize: NSSize {
return contentSize
}
override func layoutAttributesForElementsInRect(rect: NSRect) -> [NSCollectionViewLayoutAttributes] {
return layoutAttributes.values.filter { $0.frame.intersects(rect) }
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> NSCollectionViewLayoutAttributes? {
return layoutAttributes[indexPath]
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: NSRect) -> Bool {
return false
}
}
override var collectionViewContentSize
, can you printcontentSize
andself.collectionView.frame
(or assimilated)? – Citriculture