3

我需要只有简单的UICollectionViewCell样式与每个顶部的单元格。像tableview一样。但我需要动态高度依赖的内容,大小内容是评论它可以变化。如何从其内容设置动态uicollectionviewcell大小 - 以编程方式

我 viewDidLoad中:

[self.commentsCollectionView registerClass:[GWCommentsCollectionViewCell class] forCellWithReuseIdentifier:@"commentCell"]; 

在.H我:

,我#IMPORT我​​的自定义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是内容查看的直接子视图和withing的singleCommentContainerview我有UILabels,UIImageViews的等,都设置witih autolayoutcode。

但我刚刚得到的(0,0)

cgsize值我怎样才能解决这个问题得到适当的大小,我需要为每个单元?

回答

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):

https://bradbambara.wordpress.com/2014/05/24/getting-started-with-custom-uicollectionview-layouts/

+0

我有一个完整的解决方案即将推出,上面是不对的! – elliotrock

-1

添加

class func size(data: WhateverYourData) -> CGSize { /* calculate size here and  retrun it */} 

到您的自定义单元格和与其做

return cell.singleCommentContainerview.bounds.size 

它应该是

return GWCommentsCollectionViewCell.size(data) 
+0

错误的语言,问题是关于objective-c – picciano

+0

@picciano - oops。哈哈。 – HMHero

相关问题