pableiros
pableiros

Reputation: 16062

Swift - Cannot change UICollectionViewFlowLayout dynamically

On viewDidLoad I set a collectionViewLayout for a UICollectionViewCell with a UILabel saying "loading content...", when the apps fetchs the content from a server, it does something like this:

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
...
// some configuration for the layout

// here it crash:
collectionView.setCollectionViewLayout(layout, animated: true)

It crash with saying this message:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' *** First throw call stack: (0x24479b0b 0x23c36dff 0x2438a6d3 0x29275999 0x29271d13 0x29272aaf 0x28be537f 0x28be4667 0x1778dc 0x165f48 0x1661b8 0x16e774 0x16f038 0xf950c 0xf9174 0xdefb0 0xe1934 0xdf98c 0x52ed78 0x52d700 0x52bfc8 0x4df9c0 0x1531ba7 0x1531b93 0x1536659 0x2443b755 0x24439c4f 0x243881c9 0x24387fbd 0x259a4af9 0x28ac0435 0x131254 0x24034873) libc++abi.dylib: terminating with uncaught exception of type NSException

The things I did is set one collectionViewLayout replace that with another.

I tried to invalidate the layout with invalidateLayout() reloading or not reloading the collectionView before to replace the collectionViewLayout and it stills crashing.

What can I do to change the collectionViewLayout dynamically? or What am I doing wrong?

Thanks

Upvotes: 5

Views: 1622

Answers (1)

Sugihey
Sugihey

Reputation: 69

I hit the same issue for iOS9 and iOS8.

In my case, call collectionView.layoutIfNeeded() after collectionView.collectionViewLayout.invalidateLayout() to solve.

Upvotes: 6

Related Questions