对UICollectionViewLayout进行子类化并分配给UICollectionView

时间:2012-10-23 22:52:03

标签: ios uicollectionview

我有一个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。

提前感谢任何建议。

2 个答案:

答案 0 :(得分:12)

编辑:我没有注意到你已经解决了你的情况,但是我遇到了同样的问题,这就是我的情况。我将它留在这里,对于那些已经没有太多关于这个主题的人来说它可能是有用的。

在绘制时,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];
}

答案 1 :(得分:0)

Storyboard参数存在问题。从Inspector面板分配自定义UICollectionLayout。enter image description here

相关问题