设置CollectionView的单元格高度,并不会真正扩展用于滚动的单元格 [英] Setting cell height of CollectionView, doesn't really expand cell for scrolling

查看:81
本文介绍了设置CollectionView的单元格高度,并不会真正扩展用于滚动的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以设置单元格的高度,然后显示内容,但不能向下滚动视图,如果我的数组中有2个项目,则UITextView Content(在该自定义单元格中)会与开始处重叠集合视图中第二个单元格的位置:

I can set the height of the cell and the content gets displayed, but I can't scroll down the collection-view, and if I have 2 items in my array the UITextView Content (in that custom cell) overlaps the start of the 2nd cell in the collectionview:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    CustomCellView* cell = [collectionView dequeueReusableCellWithReuseIdentifier:DequeueReusableCell forIndexPath:indexPath];
    [cell setHeight: [cell calculateHeight]];
    [cell layoutIfNeeded];
    return cell;
}

推荐答案

您无法手动设置像元大小.您需要让collectionView为您布置单元格.

You can't set cell sizes manually. You need to let the collectionView layout the cells for you.

假设您使用的是Flow布局,如果想要恒定的项目大小,只需在IB或代码中在布局上设置itemSize属性即可.如果您需要动态尺寸(看起来确实如此),则需要实施以下步骤:

Assuming you're using a Flow layout, if you want a constant item size you just set the itemSize property on the layout, in IB or in code. If you need dynamic sizes, as it seems you do, you need to implement this:

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

在回答有关如何计算尺寸的问题时,我会做类似的事情:

In answer to your question about how to calculate size, I'd do something like this:

+ (CGFloat)heightForCellWithText:(NSString *)text width:(CGFloat)width
{
    UIFont *textViewFont = [UIFont systemFontOfSize:16];
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : textViewFont}];
    CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(width, FLT_MAX) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin context:nil];
    return rect.size.height;
}

这篇关于设置CollectionView的单元格高度,并不会真正扩展用于滚动的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆