ios 具有动态高度的 UICollectionView 在单元格之间没有相同的空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21526920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:20:18  来源:igfitidea点击:

UICollectionView with dynamic height not getting same space between cell

iosobjective-cipaduicollectionviewuicollectionviewcell

提问by Viral Narshana

I am having similar problem like this

我有类似的问题,这样的

I am generating height of view at run time.Here is my code

我在运行时生成视图高度。这是我的代码

@interface CollectionViewController ()
{
    NSMutableArray *arrMain;
}
@property(nonatomic,strong) NSMutableArray *arrMain;
@end

@implementation CollectionViewController
@synthesize arrMain,


- (void)viewDidLoad
{
    [super viewDidLoad];

    [cView registerNib:[UINib nibWithNibName:@"CViewCell" bundle:nil] forCellWithReuseIdentifier:kCellID];

    CViewFlowLayout *fl = [[CViewFlowLayout alloc] init];
    self.cView.collectionViewLayout = fl;

    NSString *strJson = MY FUNCTION WHICH RETURNS JSON STRING;
    SBJSON *parser = [[SBJSON alloc] init];

    self.arrMain = [[NSMutableArray alloc] init];
    self.arrMain = [parser objectWithString:strJson error:nil];
    for (int i=0; i<[self.arrMain count]; i++) {
        NSDictionary *dic = [self.arrMain objectAtIndex:i];
        [self setTags:[[UIView alloc] init] selDictionary:dic];  // This function generates height and save it to the dictionary
    }
    [cView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
    return [self.arrMain count];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    NSDictionary *dic = [self.arrMain objectAtIndex:indexPath.row];
    return CGSizeMake(236,40+[[dic valueForKey:@"TAGS_HEIGHT"] intValue]);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{

    CViewCell *cell =(CViewCell *) [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];
    NSDictionary *dic = [self.arrMain objectAtIndex:indexPath.row];
    if ([cell viewWithTag:11]){
        [[cell viewWithTag:11] release];
        [[cell viewWithTag:11] removeFromSuperview];
    }
    UIView *viewTags = [[UIView alloc] init];
    [viewTags setTag:11];
    [viewTags setBackgroundColor:[UIColor lightGrayColor]];
    [self setTags:viewTags selDictionary:dic];
    [viewTags setFrame:CGRectMake(5, 10, CONTENT_WIDTH, [[dic valueForKey:@"TAGS_HEIGHT"] floatValue])];
    [cell.contentView addSubview:viewTags];

    return cell;
}

I had tried above link solution but it is not working for me. Here is an image of my output.

我已经尝试过上面的链接解决方案,但它对我不起作用。这是我的输出图像。

I need the spacing to be same. Is anyone having solution for this issue ?

我需要间距相同。有没有人解决这个问题?

Is this bug of UICOllectionView ? Because I found this issue in this articlealso.

这是 UICOllectionView 的错误吗?因为我在这篇文章中也发现了这个问题。

采纳答案by Viral Narshana

I've got the general solution for this kind of problem:

我有这种问题的一般解决方案:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [cView registerNib:[UINib nibWithNibName:@"CViewCell" bundle:nil] forCellWithReuseIdentifier:kCellID];

    CViewFlowLayout *fl = [[CViewFlowLayout alloc] init];
    fl.minimumInteritemSpacing = 10;
    fl.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.cView.collectionViewLayout = fl;

    NSString *strJson = MY FUNCTION WHICH RETURNS JSON STRING;
    SBJSON *parser = [[SBJSON alloc] init];

    self.arrMain = [[NSMutableArray alloc] init];
    self.arrMain = [parser objectWithString:strJson error:nil];
    for (int i=0; i<[self.arrMain count]; i++) {
    NSDictionary *dic = [self.arrMain objectAtIndex:i];
    [self setTags:[[UIView alloc] init] selDictionary:dic];  // This function generates height and save it to the dictionary
}
    [cView reloadData];

}

}

Then, update the code in CViewFlowLayout.m, which is a subclass of UICollectionViewFlowLayout.

然后,更新 CViewFlowLayout.m 中的代码,它是UICollectionViewFlowLayout.

Here is the code:

这是代码:

#define numColumns 3
@implementation CViewFlowLayout
@synthesize numOfColumnsToDisplay;
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn)
    {
        if (nil == attributes.representedElementKind)
        {
            NSIndexPath* indexPath = attributes.indexPath;
            attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
        }
    }
    return attributesToReturn;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes* currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];

    if (indexPath.item < numColumns){
        CGRect f = currentItemAttributes.frame;
        f.origin.y = 0;
        currentItemAttributes.frame = f;
        return currentItemAttributes;
    }
    NSIndexPath* ipPrev = [NSIndexPath indexPathForItem:indexPath.item-numColumns inSection:indexPath.section];
    CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame;
    CGFloat YPointNew = fPrev.origin.y + fPrev.size.height + 10;
    CGRect f = currentItemAttributes.frame;
    f.origin.y = YPointNew;
    currentItemAttributes.frame = f;
    return currentItemAttributes;
}

This solution will work for vertical scrolling only. If you want to display more or less columns, just change the numColumns.

此解决方案仅适用于垂直滚动。如果要显示更多或更少的列,只需更改numColumns.

回答by Rajesh Loganathan

Try this:

尝试这个:

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

    return CGSizeMake(250, 150);
}

回答by Kumar KL

You can set the size with a property:

您可以使用属性设置大小:

flowLayout.headerReferenceSize = CGSizeMake(0, 100);//constant height for all the items header

If Dynamic :

如果动态:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == albumSection) {
        return CGSizeMake(0, 100);
    }

    return CGSizeZero;
}

回答by Muralikrishna

See this in Storybord or xib set values! enter image description here

在 Storybord 或 xib 设置值中看到这个! 在此处输入图片说明

回答by Swati

The class that you inherited from UICollectionViewFlowLayoutmust contain methods :

您继承的类UICollectionViewFlowLayout必须包含方法:

- (CGSize)collectionViewContentSize
{
    return CGSizeMake(200, 200) // as per your cell size
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn)
    {
        if (nil == attributes.representedElementKind)
        {
            NSIndexPath* indexPath = attributes.indexPath;
            attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
        }
    }
    return attributesToReturn;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes* currentItemAttributes =
    [super layoutAttributesForItemAtIndexPath:indexPath];

    if (!currentItemAttributes)
    {
        currentItemAttributes = [UICollectionViewLayoutAttributes
                                 layoutAttributesForCellWithIndexPath:indexPath];
    }
    return currentItemAttributes;
}

And in Your CollectionViewController add

并在您的 CollectionViewController 添加

#pragma mark - Collection View Datasource

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout  *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // Adjust cell size for orientation
    if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
    {
        return CGSizeMake(150, 230);
    }
    return CGSizeMake(150, 230);
}

回答by Sankalp S Raul

Using following method

使用以下方法

//Swift

//迅速

func collectionView(_ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
 return CGSizeMake(250, 150);
}

//Objective C

//目标C

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(250, 150);
}