对UICollectionViewLayout进行子类化并分配给UICollectionView [英] Subclassing UICollectionViewLayout and assign to UICollectionView
问题描述
我有一个CollectionViewController
I have a CollectionViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// assign layout (subclassed below)
self.collectionView.collectionViewLayout = [[CustomCollectionLayout alloc] init];
}
// data source is working, here's what matters:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ThumbCell *cell = (ThumbCell *)[cv dequeueReusableCellWithReuseIdentifier:@"ThumbCell" forIndexPath:indexPath];
return cell;
}
我还有一个UICollectionViewLayout子类:CustomCollectionLayout.m
I also have a UICollectionViewLayout subclass: CustomCollectionLayout.m
#pragma mark - Overriden methods
- (CGSize)collectionViewContentSize
{
return CGSizeMake(320, 480);
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
return [[super layoutAttributesForElementsInRect:rect] mutableCopy];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
// configure CellAttributes
cellAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
// random position
int xRand = arc4random() % 320;
int yRand = arc4random() % 460;
cellAttributes.frame = CGRectMake(xRand, yRand, 150, 170);
return cellAttributes;
}
我正在尝试为单元格使用新框架,只需要一个一个随机的位置。
问题是没有调用layoutAttributesForItemAtIndexPath。
I'm trying to use a new frame for the cell, just one at a random position. The problem is layoutAttributesForItemAtIndexPath is not called.
提前感谢任何建议。
推荐答案
编辑:我没有注意到你已经解决了你的情况,但我遇到了同样的问题,这就是我的情况。我将它留在这里,它可能对某人有用,因为这个主题还不多。
I didn't notice that you've solved your case, but I had the same problem and here's what helped in my case. I'm leaving it here, it may be useful for someone given that there's not much on this topic yet.
绘图时, UICollectionView
不会调用方法 layoutAttributesForItemAtIndexPath:
但 layoutAttributesForElementsInRect:
以确定哪些单元格应该可见。您有责任实现此方法,并从那里调用 layoutAttributesForItemAtIndexPath:
获取所有可见索引路径以确定确切位置。
Upon drawing, UICollectionView
does not call the method layoutAttributesForItemAtIndexPath:
but layoutAttributesForElementsInRect:
to determine which cells should be visible. It's your responsibility to implement this method and from there call layoutAttributesForItemAtIndexPath:
for all visible index paths to determine exact locations.
换句话说,将其添加到您的布局:
In other words, add this to your layout:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray * array = [NSMutableArray arrayWithCapacity:16];
// Determine visible index paths
for(???) {
[array addObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:??? inSection:???]]];
}
return [array copy];
}
这篇关于对UICollectionViewLayout进行子类化并分配给UICollectionView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!