我有一个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
#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.
提前感谢任何建议.
解决方法
编辑:我没有注意到你已经解决了你的情况,但我遇到了同样的问题,这就是我的情况.我将它留在这里,对于那些已经没有太多关于这个主题的人来说它可能是有用的.
在绘制时,UICollectionView不会调用方法layoutAttributesForItemAtIndexPath:但layoutAttributesForElementsInRect:以确定哪些单元格应该可见.您有责任实现此方法,并从那里调用layoutAttributesForItemAtIndexPath:用于所有可见索引路径以确定确切位置.
换句话说,将其添加到您的布局:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArray * array = [NSMutableArray arrayWithCapacity:16]; // Determine visible index paths for(???) { [array addObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:??? inSection:???]]]; } return [array copy]; }