3782

Application crash when set header of UICollectionView horizontally

I am pretty new in UICollectionView. And I am really tired to find out the solution. I am trying to add Header in 3 Horizontally Row. I am using Collection view flow layout. Here is my code which I implement:

- (void)awakeFromNib { self.collectionView.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0]; self.collectionView.backgroundColor = [UIColor clearColor]; self.collectionView.backgroundView = [[UIView alloc] initWithFrame:CGRectZero]; UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; flowLayout.itemSize = CGSizeMake(130.0, 170.0); [self.collectionView setCollectionViewLayout:flowLayout]; // Register the colleciton cell [_collectionView registerNib:[UINib nibWithNibName:@"ORGArticleCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ORGArticleCollectionViewCell"]; [self.collectionView registerClass:[_HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"]; } #pragma mark - UICollectionViewDataSource methods - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { if (section == 0) { return [self.collectionData count]; } else if(section == 1) { return [self.collectionData1 count]; } else { return [self.collectionData2 count]; } } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { ORGArticleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ORGArticleCollectionViewCell" forIndexPath:indexPath]; cell.articleTitle.text = [self.collectionData objectAtIndex:[indexPath row]]; NSString *URL = [self.collectionImageData objectAtIndex:indexPath.row]; [cell.articleImage setImageWithURL:[NSURL URLWithString:URL] placeholderImage:[UIImage imageNamed:@"profile-image-placeholder"]]; cell.articleImage.contentMode = UIViewContentModeScaleToFill; cell.articlePrice.text = [self.collectionDataPric objectAtIndex:[indexPath row]]; return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *cellData = [self.collectionData objectAtIndex:[indexPath row]]; [[NSNotificationCenter defaultCenter] postNotificationName:@"didSelectItemFromCollectionView" object:cellData]; } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 0; } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { return 0; } - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind: UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; UILabel *label = (UILabel *)[headerView viewWithTag:10]; if (!label) { label = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 5, 5)]; label.tag = 10; label.font = [UIFont boldSystemFontOfSize:12]; label.textColor = [UIColor darkGrayColor]; [headerView addSubview:label]; } label.text = [NSString stringWithFormat:@"Section %d", indexPath.section]; return headerView; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section { CGSize headerSize = CGSizeMake(320, 44); return headerSize; }

My App crash in viewForSupplementaryElementOfKind method when I initialize the header view. Following are the crash log:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionHeader at path {length = 2, path = 0 - 0}'

Answer1:

The problem with your code is [headerView addSubview:label]; this is called only when label is equal to nil. but you have to call this statement every time when viewForSupplementaryElementOfKind is called.

Update your viewForSupplementaryElementOfKind function with following code.

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind: UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; UILabel *label = (UILabel *)[headerView viewWithTag:10]; if (!label) { label = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 5, 5)]; label.tag = 10; label.font = [UIFont boldSystemFontOfSize:12]; label.textColor = [UIColor darkGrayColor]; } label.text = [NSString stringWithFormat:@"Section %d", indexPath.section]; [headerView addSubview:label]; return headerView; }

Recommend

  • How to change the border style of applications main window in visual c++ win32 API
  • How to eliminate variables “panel1, panel2, panel3 .. etc.” in Delphi?
  • IOS UICollectionView with ScrollView
  • UICollectionview footer in swift
  • Set UITableView BackgroundColor Universally with UIAppearance
  • NSFetchedResultsController doesn't always call didChangeObject:atIndexPath:forChangeType:newInd
  • Facebook iOS SDK: presentFeedDialogModallyWithSession crashes
  • EMACS rebinding C-spc disable highlight of selected region
  • Delete object in core data, failed to match the Swift Array Element type
  • updatesearchresultsforsearchcontroller not called
  • How to use CKFetchNotificationChangesOperation?
  • Why the query doesn't return results when the ancestor is not provided?
  • Passing argument within action selection in UIButton
  • Memory leak when filtering with Core image
  • How to Navigate from Initial UIViewController to UISplitViewController in Swift
  • string.find failed on Chinese character in Android but success on PC when developing cocos-lua game
  • NSOpenPanel's setDirectoryURL doesn't work on Lion
  • RDF - Distributing rdf:type to all items in the list
  • Multiple storyboards: should I use a singleton pattern to cache them?
  • “[CALayer release]: message sent to deallocated instance” when dismissing modal view controller
  • OSStatus error -50 (invalid parameters) AudioQueueNewInput recording audio on iOS
  • Why can't I extract data from media file using AVURLAsset in a Playground?
  • iOS 9 custom transition - animationControllerForDismissedController not called
  • UIScrollView setContentOffset: animated: not working
  • Why does Apple use assign rather than weak to store a delegate?
  • Installing libCurl - ruby 1.9.3 .. rails 3.2.12 .. Windows
  • Cannot page through all results using nextPageToken on YouTube search API v3
  • How to create a new Bundle object?
  • Should a web service response include empty values?
  • How to get listview position?
  • How to access profile picture with Facebook API in Swift 3?
  • UIAlertController button function not working
  • How to remove a SwiftyJSON element?
  • Connect .sks to skscene.h
  • How to test if a URL from an Eclipse bundle is a directory?
  • Row Count Is Returning the incorrect number using RaptureXML
  • Obtain ObjectIdHex value from mgo query
  • Cannot Parse HTML Data Using Android / JSOUP
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • Bitwise OR returns boolean when one of operands is nil