Trying to add a a Supplementary view into my UICollectionView
as a header. I\'m having issues getting it to work.
I use a custom UICollectionViewFlowL
I also got this annoying error:
*** Assertion failure in -[UICollectionView _createPreparedSupplementaryViewForElementOfKind:atIndexPath:withLayoutAttributes:applyAttributes:], /SourceCache/UIKit/UIKit-3347.44/UICollectionView.m:1400
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView dataSource is not set'
and I found some people solving this error by doing
- (void)dealloc {
self.collectionView = nil;
}
or in swift:
deinit {
collectionView = nil
}
however neither of these solved my crash. I tried a few things out and the following "hack" solved this annoying bug:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if collectionView.dataSource != nil {
return someHeaderSize
} else {
return CGSizeZero
}
}
The answers in this topic are quite old, and do not work in iOS8 and iOS9. If you are still having the described issue, check out the following topic: UICollectionView and Supplementary View crash
EDIT:
Here is the answer, in case the link becomes invalid:
If you are using custom layout in your collection view, check if its datasource is nil in:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
The result should look something like this:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
if (self.collectionView.dataSource != nil) {
// Your layout code
return array;
}
return nil;
}
This change resolves the following issue:
- Assertion failure in -[UICollectionView _createPreparedSupplementaryViewForElementOfKind:atIndexPath:withLayoutAttributes:applyAttributes:]
You can also check the following topic, however it didn't resolve anything in my case:
Removing empty space, if the section header is hidden in the UICollectionView
Hope it will help you, and you won't waste as much time as I did.
Try this :
self.collectionView?.dataSource = nil
self.collectionView = nil
It worked for me ;)
A iOS9 bug, In viewcontroller's dealloc set layer delegate nil.
- (void)dealloc{
if ([[[UIDevice currentDevice] systemVersion] hasPrefix:@"9"]) {
self.collectionView.layer.delegate = nil;
}
}