Skip to content

Instantly share code, notes, and snippets.

@james-b-kelly
Last active August 29, 2015 14:07
Show Gist options
  • Save james-b-kelly/c3f55f8c4cda677ce951 to your computer and use it in GitHub Desktop.
Save james-b-kelly/c3f55f8c4cda677ce951 to your computer and use it in GitHub Desktop.
Multi-line UIlLabel in full-width UICollectionViewCell.
//In your UIViewController (containing the UICollectionView).
//In @interface
@property (nonatomic, strong) MyCollectionViewCellSubclass *prototypeCell;
//In viewDidLoad
//Register your subclassed cell, and load your prototype cell.
UINib *cellNib = [UINib nibWithNibName:@"MyCollectionViewCellSubclass" bundle:nil];
[collectionView registerNib:cellNib forCellWithReuseIdentifier:@"MyCollectionViewCellSubclassID"];
self.prototypeCell = [cellNib instantiateWithOwner:nil options:nil][0];
//Add this delegate method.
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//Populate your cell the same way you do in cellForItemAtIndexPath:.
//Here I have a method to do that:
[self populateCell:self.prototypeCell atIndexPath:indexPath];
//This line forces the label to it's max width.
self.prototypeCell.label.preferredMaxLayoutWidth = self.prototypeCell.label.frame.size.width;
CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
//Make sure the cell fills the horizontal space.
size.width = CGRectGetWidth(collectionView.frame);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment