I am creating on UICollectionView
for showing some data which are coming from server. But I have to set that cell height dynamically according to text size. I am creating a custom cell for UICollectionView
.
Retrieve that UICollectionView
cell in my ViewDidLoad
method:
UINib *cellNib = [UINib nibWithNibName:@"Custom_CollectionViewCell" bundle:nil];
[self.noteBookmarkCollectinView registerNib:cellNib forCellWithReuseIdentifier:@"CustomCell"];
Below Delegate method for UICollectionView
:
#pragma mark Collection view layout things
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return noteDetailsArr.count;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 4.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 4.0;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0,4,0,4); // top, left, bottom, right
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(154, 154); // This is my fixed Cell height
//Before I am trying this below code also, but its not working
return [(NSString*)[contentArr objectAtIndex:indexPath.row] sizeWithAttributes:NULL];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"CustomCell";
Custom_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.contentLbl.numberOfLines = 0;
cell.contentLbl.tag = indexPath.row;
cell.contentLbl.text = [contentArr objectAtIndex:indexPath.row];
[cell.contentLbl sizeToFit];
return cell;
}
My result is coming like this :
Notes: Green color is Cell background color & Pink color is label BG Color.
And when I scroll the CollectionView
I am able to see like below Image & After scroll again its coming perfect (Only for last row)
How can I make the cell height dynamically according to text. please Help me. I am stuck from last 1 week.