2012-10-23 33 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

相關問題