Ios 如何以编程方式从内容设置动态uicollectionviewcell大小

Ios 如何以编程方式从内容设置动态uicollectionviewcell大小,ios,objective-c,uicollectionview,uicollectionviewcell,contentsize,Ios,Objective C,Uicollectionview,Uicollectionviewcell,Contentsize,我需要一个简单的UICollectionViewCell样式,每个单元格上都有单元格。像tableview。但我需要动态高度依赖的内容,大小的内容是评论它可以变化 我得到 viewDidLoad: [self.commentsCollectionView registerClass:[GWCommentsCollectionViewCell class] forCellWithReuseIdentifier:@"commentCell"]; 在.h中,我得到: 我#导入我的自定义UICo

我需要一个简单的UICollectionViewCell样式,每个单元格上都有单元格。像tableview。但我需要动态高度依赖的内容,大小的内容是评论它可以变化

我得到 viewDidLoad:

  [self.commentsCollectionView registerClass:[GWCommentsCollectionViewCell class] forCellWithReuseIdentifier:@"commentCell"];
在.h中,我得到:

我#导入我的自定义UICollectionViewCell,它使用编程自动布局设置所有约束

我使用以下命令实例化UICollectionView:

UICollectionViewFlowLayout *collViewLayout = [[UICollectionViewFlowLayout alloc]init];
self.commentsCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:collViewLayout];
我使用autolatyout使UICollectionView位于我想要的位置(这就是为什么CGRectZero)

最后我希望这样做:

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    GWCommentsCollectionViewCell *cell = (GWCommentsCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];

    return cell.singleCommentContainerview.bounds.size;
}
singleCommentContainerview是contentView的一个直接子视图,使用singleCommentContainerview,我有UILabels、UIImageView等,所有这些都设置为自动布局代码

但是我只得到了cgsize的值(0,0)


如何解决此问题以获得每个单元格所需的适当大小?

根据我所阅读的UICollectionView需要在布局单元格之前计算出大小。你上面的方法是,细胞还没有被画出来,所以它没有大小。此外,它可能是一个问题,也可能与使用相同标识符@“commentCell”缓存/合并单元格的问题相结合,我通常使用新的标识符和类标记唯一的单元格

我的想法是在绘制单元格之前捕获单元格,将大小放入字典,以便以后使用,使用:

- (void)collectionView:(UICollectionView *)collectionView
       willDisplayCell:(UICollectionViewCell *)cell
    forItemAtIndexPath:(NSIndexPath *)indexPath{

GWCommentsCollectionViewCell *cell = (GWCommentsCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
// Need to add it to the view maybe in order for it the autolayout to happen
[offScreenView addSubView:cell];
[cell setNeedsLayout];

CGSize *cellSize=cell.singleCommentContainerview.bounds.size
NSString *key=[NSString stringWithFormat:@"%li,%li",indexPath.section,indexPath.row];
// cellAtIndexPath is a NSMutableDictionary  initialised and allocated elsewhere
[cellAtIndexPath setObject:[NSValue valueWithCGSize:cellSize] forKey:key]; 

}
然后,当您需要它时,使用基于键的字典来获取大小

这并不是一个非常漂亮的方式,因为它依赖于正在绘制的视图,在获得尺寸之前,自动布局会完成它的工作。如果你正在加载更多的图像,它可能会引发一些问题

也许更好的方法是对尺寸进行预编程。如果您有图像尺寸方面的数据,可能会有所帮助。查看这篇文章以获得一个非常好的教程(是的,编程上没有IB):

添加

class func size(data: WhateverYourData) -> CGSize { /* calculate size here and     retrun it */} 
到您的自定义单元格,而不是执行

return cell.singleCommentContainerview.bounds.size
应该是

return GWCommentsCollectionViewCell.size(data)

@皮奇亚诺-哎呀。哈哈。我很快就会有一个完整的解决方案,上面说的不对!