如何从collectionview的数据源中获取项目数

 xinzhugedonny 发布于 2023-01-31 16:22

我是新手Collectionview,但不是iOS.我在我的collectionview中使用自定义Flowlayout.我需要根据CollectionView的数据源返回的当前项目数返回contentize.无论如何知道flowlayout的collectionview中有多少项目?

@interface LatestNewsFlowLayout : UICollectionViewFlowLayout

-(id)initWithSize:(CGSize) size;

@end

@implementation LatestNewsFlowLayout

-(id)initWithSize:(CGSize) size {
    self = [super init];
    if (self) {
        self.itemSize = size;
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.sectionInset = UIEdgeInsetsMake(0, 10.0, 0, 0);
        self.minimumLineSpacing = 5;
    }
    return self;
}

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

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    for(int i = 1; i < [answer count]; ++i) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
        UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
        NSInteger maximumSpacing = 5;
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }

    return answer;
}

-(CGSize) collectionViewContentSize
{
    CGSize size;
    int numOfItems = ???
    size.width = 100 * numOfItems;
    size.height = 100;
    return size;
}

George Green.. 22

UICollectionViewFlowLayout是UICollectionViewLayout的子类.因此它应该可以访问UICollectionView,它应该知道有多少项.

[self.collectionView numberOfItemsInSection:0];

如果您有多个部分,则可能需要迭代该部分以获取项目总数.

您可以类似地获得部分的数量:

[self.collectionView numberOfSections];

希望这可以帮助!:)

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有