ios - 在非滚动 UICollectionView 中动态调整 UICollectionViewCell 的大小

标签 ios objective-c uicollectionview uicollectionviewcell uicollectionviewlayout

我在屏幕顶部有一个小的单行水平布局 UICollectionView。它最多可以包含 6 个项目。问题是我希望所有 6 个项目都可见而不滚动(这个 Collection View 也将用于不允许滚动的 Today 扩展)。我想要做的是稍微减小单元格大小和项目间间距,以允许所有 6 个单元格适合。

基本上我试图避免这种情况:

enter image description here

我已经玩了一段时间了,但我不知道如何处理它。我创建了一个方法,每次在 Collection View 中添加或删除项目时都会触发它,就在 [self.collectionview reloadData] 之前。叫做。

-(void)setupCollectionViewLayout{

     UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

        //Figure out if cells are wider than screen
    CGFloat screenwidth = self.view.frame.size.width;

    CGFloat sectionInsetLeft = 10;
    CGFloat sectionInsetRight = 10;
    CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing;
    CGSize  itemsize = CGSizeMake(58,58);
    CGFloat itemsizeWidth = itemsize.width;
    CGFloat totalWidth = sectionInsetLeft + sectionInsetRight +
                        (itemsizeWidth * _armedRemindersArray.count) +
                        (minItemSpacing * (_armedRemindersArray.count -2));


    CGFloat reductionAmount = itemsizeWidth;
    if (totalWidth > screenwidth) {


        while (totalWidth > screenwidth) {
            totalWidth = totalWidth - 1;
             reductionAmount = reductionAmount - 1;
        }


        CGSize newCellSize = CGSizeMake(reductionAmount, reductionAmount);
        flowLayout.itemSize = newCellSize;

    }

    else flowLayout.itemSize = itemsize;

}

这就是结果。

enter image description here

不完全是我所期待的。它不仅将所有内容都压缩到左侧并添加了第二行,而且我似乎也遇到了单元重用问题。老实说,如果它甚至是一个选项,我只会使用静态单元格,但不幸的是,这似乎是不可能的。

我应该做什么?子类化 UICollectionViewFlowLayout?这不会基本上和我在这里使用内置流布局做同样的事情吗?

编辑:
Kujey 的回答肯定更接近我的需要。我仍然有一个细胞重用问题。
enter image description here

最佳答案

Xcode 提供了一个为您的需要而设计的对象。它被称为 UICollectionViewFlowLayout ,您需要做的就是将其子类化并按照您想要的方式放置您的单元格。每次 Collection View 需要更新布局时,都会调用函数 prepareForLayout。
您需要的代码如下:

#import "CustomLayout.h"

#define MainCell @"MainCell"

@interface CustomLayout ()

@property (nonatomic, strong) NSMutableDictionary *layoutInfo;

@end

@implementation CustomLayout


-(NSMutableDictionary *) layoutInfo
{
    if (!_layoutInfo) {
        _layoutInfo = [NSMutableDictionary dictionary];
    }

    return _layoutInfo;
}

-(void) prepareLayout
{
    NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary];

    NSIndexPath *indexPath;

    CGFloat itemWidth;
    CGFloat itemSpacing;

    CGFloat widthWithoutSpacing = [self collectionViewContentSize].width / ([self.collectionView numberOfItemsInSection:0]);

    if (widthWithoutSpacing > [self collectionViewContentSize].height) {
        itemWidth = [self collectionViewContentSize].height;
        itemSpacing = ([self collectionViewContentSize].width - itemWidth*[self.collectionView numberOfItemsInSection:0])/
        ([self.collectionView numberOfItemsInSection:0]+1);
    }
    else {
        itemWidth = widthWithoutSpacing;
        itemSpacing = 0;
    }

    CGFloat xPosition = itemSpacing;

    for (NSInteger section = 0; section < [self.collectionView numberOfSections]; section++) {

        for (NSInteger index = 0 ; index < [self.collectionView numberOfItemsInSection:section] ; index++) {

            indexPath = [NSIndexPath indexPathForItem:index inSection:section];
            UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

            CGRect currentFrame=itemAttributes.frame;

            currentFrame.origin.x = xPosition;
            currentFrame.size.width = itemWidth;
            currentFrame.size.height = itemWidth;

            itemAttributes.frame=currentFrame;
            cellLayoutInfo[indexPath] = itemAttributes;

            xPosition += itemWidth + itemSpacing;
        }
    }

    self.layoutInfo[MainCell] = cellLayoutInfo;
}


- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}


- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];

    [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier, NSDictionary *elementsInfo, BOOL *stop) {
        [elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop) {
            if (CGRectIntersectsRect(rect, attributes.frame)) {
                [allAttributes addObject:attributes];
            }
        }];
    }];

    return allAttributes;
}


-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return self.layoutInfo[MainCell][indexPath];
}


-(CGSize) collectionViewContentSize
{
    return self.collectionView.frame.size;
}



@end

如果需要将单元格垂直居中,还可以更改单元格的 y 原点。

关于ios - 在非滚动 UICollectionView 中动态调整 UICollectionViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28131440/

相关文章:

ios - Flutter - 使用 google_maps_webservice 和 google_maps_flutter 的附近地点

ios - 如何以编程方式激活 ios 通知设置?

ios - 如何更改视频播放速度

objective-c - 如何在 Objective-C 中将 NSView 转换为 NSTableView

ios - 自定义 UICollectionViewCell 增加内存分配

ios - NSJSONSerializer 如何确定给定数据的编码?

ios - 从 UITextField 继承的自定义类在 Swift 中不起作用(使用自定义 init)

ios - UI : iOS 中动态数据的 UI 单元测试失败

ios - UICollectionView 的水平流

objective-c - Collection View 布局