Dynamic Size for NSCollectionViewItem

933 views Asked by At

I am trying to give a dynamic size to my NSCollectionViewItem. I want them to have a size determine by their content and the constraint I defined.

For that I have add to my viewcontroller which holds the NSCollectionView the following :

extension ViewController :  NSCollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize{

        let item = collectionView.item(at: indexPath)
        if let viewItem = item as NSCollectionViewItem? {
            return viewItem.view.fittingSize
        }

        return NSSize(width: 200, height: 100)

    }
}

Which throw an exception.

An uncaught exception was raised
*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]

I don't see where it come from, I tried to catch it but xcode says that item(at:) don't throws exception.

Edit: but in fact it does, I had an exception breakpoint and it break in item(at:) item(at:) exception

Beside sending a bug repport to Apple does someone have an other idea ? And since item(at:) is not supposed to throw error a do catch bloc is ineffective

2

There are 2 answers

0
Rémy Virin On

As you mention, I Don't think this method is crashing. From the documentation:

Return: The item for the specified index path or nil if no item is available.

Have you try to add an exception breakpoint? You should see where it's crashing.

0
Tony AH On

sizeForItemAtIndexPath calling before creating a UICollectionViewItem, so it's impossible to do it.