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

标签 ios objective-c uicollectionview uicollectionviewcell contentsize

我只需要简单的 UICollectionViewCell 样式,单元格位于每个单元格之上。像 TableView 。但是我需要依赖于内容的动态高度,内容的大小是可以变化的评论。

我得到了 查看加载:

  [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 是 contentView 的直接 subview ,通过 singleCommentContainerview 我有 UILabels、UIImageViews 等,所有设置都带有自动布局代码。

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

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

最佳答案

根据我的阅读,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]; 

}

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

这不是一个真正 super 漂亮的方式,因为它依赖于正在绘制的 View ,自动布局在您获得尺寸之前完成它的事情。如果您要加载更多图片,可能会引发问题。

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

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

关于ios - 如何从其内容设置动态 uicollectionviewcell 大小 - 以编程方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640799/

相关文章:

ios - 一页横向模式 swift

iOS OneDrive (skydrive) 应用程序每次运行时都会显示权限对话框

objective-c - 将 .plist 文件与 iCloud 同步

swift - 重新加载没有动画 Swift 的 Collection View

ios - 收藏 View 未正确显示图像

ios - Ionic 3 - 使用 Google map /Apple map 应用程序无需导航即可打开地理定位

ios - 可转换数据和二进制数据有什么区别

ios - 无法更改自定义 UITableViewCell 中 UILabel 的大小

ios - 过渡导航栏标题

ios - 从非协议(protocol)类型 'UICollectionViewFlowLayout' 继承