2012-10-23 38 views
8

我有一个CollectionViewController子类UICollectionViewLayout并分配给UICollectionView

- (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未被调用。

在此先感谢您的任何建议。

+0

有谁知道在哪里找到UICollectionViewLayout自定义实现样品? – brainondev

+3

你可以在https://github.com/jayslu/JSPintDemo看看我的Pinterest启发UICollectionViewLayout –

+0

非常有趣的Jay ...感谢分享! – brainondev

回答

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]; 
} 
+2

你能代替“???”吗?具有适当的价值? – Philip007

+2

如果'layoutAttributesForItemAtIndexPath:'没有被'UICollectionViewLayout'中的绘图代码调用,那么为什么它在类的接口?! – fatuhoku

+1

传统?较旧的API?计划的API?建议一个好的模式?好问题! –

0

是故事板参数的问题。从Inspector面板分配自定义的UICollectionLayout。 enter image description here

+0

我复制你的代码并运行它。就像你说的那样,不调用'layoutAttributesForItemAtIndexPath'。但是在更改故事板中的布局类后,问题仍然存在。你确定你在这里发布的代码与你实际使用的代码完全相同吗? – Philip007

+0

我从来没有说过,上面发布的代码是一个工作代码。这只是我将CustomLayout分配给UICollectionView的一个地方。对于一个好的工作代码,我建议你看一下Jay Slupesky发布的链接......它对我有很大的帮助。 – brainondev

+1

你接受你自己的答案,不解决问题中的代码。这看起来很具误导性。 – Philip007

相关问题