2015-05-01 34 views
1

我正在創建一個collectionView,其單元格的大小和內容不同。我使用的是電池原型,這些細胞,但是,當我加入一個以上的小區我得到奇怪的UI錯誤:collectionView可重複使用的單元格導致錯誤

這是它應該看起來像 Supposed to 這是它實際上看起來像 Fail

代碼:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    Card *card = [[[usermanager getSelectedUser] getCards] objectAtIndex:indexPath.item]; 

    [card setupLayout]; 

    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; 
    if(cell == nil){ 
     cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath]; 
    } 
    [cell addSubview:card]; 
    cell.clipsToBounds = YES; 
    cell.layer.shouldRasterize = YES; 
    cell.layer.rasterizationScale = [UIScreen mainScreen].scale; 

    cell.layer.shadowPath = [[UIBezierPath bezierPathWithRect:cell.bounds] CGPath]; 

    //Add dropshadow 
    cell.contentView.layer.borderWidth = 1.0f; 
    cell.contentView.layer.borderColor = [UIColor clearColor].CGColor; 
    cell.contentView.layer.masksToBounds = YES; 

    cell.layer.shadowColor = [UIColor blackColor].CGColor; 
    cell.layer.shadowOffset = CGSizeMake(0, 5.0f); 
    cell.layer.shadowRadius = 2.0f; 
    cell.layer.shadowOpacity = 0.5f; 
    cell.layer.masksToBounds = NO; 

    cell.layer.borderColor = [UIColor yellowColor].CGColor; 
    cell.layer.borderWidth = 2.0f; 

    return cell; 
} 

它propably有事情做的事實,我用的是可重複使用的電池。因爲當我在故事板中爲這些單元格創建2個不同的原型時,它們根本沒有問題。誰能幫我?謝謝

+1

第一件事我會嘗試是創建一個自定義'CardCollectionViewCell'從'UICollectionViewCell'繼承並實現'prepareForReuse'方法。目前尚不清楚你是否已經重新使用了你的例子中的任何單元,所以這可能沒有幫助,但是我懷疑你需要一個單元重新使用。 我想知道的第二件事是如果您更改單元格的大小與卡子視圖相同會發生什麼情況。 第三,我不確定默認佈局如何處理不同大小的單元格。您可能需要繼承'UICollectionViewLayout'並計算單元格位置。 –

+0

你如何設置你的細胞的大小?或者你正在使用動態單元格大小? – Davuth

+0

是否有可能使兩個子類具有不同的標識符? – nacho4d

回答

4

正如你所說:你的單元格將被重用,所以如果你改變任何佈局或框架或顏色,這些屬性就像你設置下一次單元格一樣。你應該繼承UICollectionViewCell和實施,你必須在細胞的所有意見和屬性重置爲初始值的方法prepareForReuse,你必須刪除子視圖卡:

-(void)prepareForReuse { 
    [super prepareForReuse]; 
    // Reset all, for example backgroundView 
    self.backgroundView = nil; 
} 

多說一點:爲什麼你叫UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];那不正確。你只需要UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];

+1

你是propably權利,而最後一件事是一個測試,我看看有沒有什麼改變任何東西 –

相關問題