如何在iOS中动态更改UICollectionView单元格高度

时间:2015-03-23 05:37:58

标签: ios objective-c uicollectionviewcell

我在UICollectionView上创建,用于显示来自服务器的一些数据。但我必须根据文本大小动态设置单元格高度。我正在为UICollectionView创建自定义单元格。

在我的UICollectionView方法中检索ViewDidLoad个单元格:

UINib *cellNib = [UINib nibWithNibName:@"Custom_CollectionViewCell" bundle:nil];
[self.noteBookmarkCollectinView registerNib:cellNib forCellWithReuseIdentifier:@"CustomCell"];

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;
}

我的结果是这样的:

enter image description here

注意:绿色是细胞背景颜色&粉红色是BG Color标签。

当我滚动CollectionView时,我可以看到如下图像&再次滚动它即将到来的完美(仅限最后一行)

enter image description here

如何根据文本动态制作单元格高度。请帮我。我被困在最后一周。

1 个答案:

答案 0 :(得分:0)

希望有所帮助

#pragma mark <UICollectionViewDelegate>
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    NSString * string = [self.array objectAtIndex:indexPath.row]


    //CALCULATE text SIZE:
    CGSize textSize = [string sizeWithAttributes:NULL];
    return textSize;
}