UICollectionViewFlowLayout 子类不起作用
Posted
技术标签:
【中文标题】UICollectionViewFlowLayout 子类不起作用【英文标题】:UICollectionViewFlowLayout subclass not working 【发布时间】:2014-04-12 19:17:09 【问题描述】:这是我的 UICollectionViewFlowLayout 子类:
@implementation MyCollectionViewFlowLayout
- (id)init
self = [super init];
if (self)
[self setup];
return self;
- (void)setup
self.itemSize = CGSizeMake(320, 320);
self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
self.minimumInteritemSpacing = 0;
self.minimumLineSpacing = 0;
self.scrollDirection = UICollectionViewScrollDirectionVertical;
- (void)prepareLayout
[super prepareLayout];
- (CGSize)collectionViewContentSize
return self.itemSize;
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
NSArray* allAttributesInRect = [super layoutAttributesForElementsInRect:rect];
return allAttributesInRect;
- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
UICollectionViewLayoutAttributes* attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
return attributes;
@end
当我执行以下操作时,集合视图将不会滚动:
MyCollectionViewFlowLayout* flowLayout = [[MyCollectionViewFlowLayout alloc] init];
但是,如果我这样做:
UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = CGSizeMake(320, 320);
flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
然后集合视图滚动正常。我在 UICollectionViewFlowLayout 子类中做错了什么?
【问题讨论】:
【参考方案1】:问题是collectionViewContentSize
- (CGSize)collectionViewContentSize
return self.itemSize;
这里返回itemSize意味着你的collection view的整个contentSize只有一个item的大小。尝试删除该代码,或将其更改为
- (CGSize)collectionViewContentSize
[super collectionViewContentSize];
【讨论】:
你甚至不需要实现这些,超类应该为流布局实现它。以上是关于UICollectionViewFlowLayout 子类不起作用的主要内容,如果未能解决你的问题,请参考以下文章