7

已經問了幾次這個問題,但沒有一個答案足夠詳細,我不能理解爲什麼/如何工作。參考其他SO問題是:使用invalidateLayout加載數據後調整UICollectionViewCell的大小

How to update size of cells in UICollectionView after cell data is set?

Resize UICollectionView cells after their data has been set

Where to determine the height of a dynamically sized UICollectionViewCell?

我使用MVC,但爲了簡單起見,您說,我有一個視圖控制器,在viewWillAppear中調用web服務來加載一些數據。當數據被加載它調用

[self.collectionView reloadData] 

的self.collectionView包含1 UICollectionViewCell(姑且稱之爲DetailsCollectionViewCell)。

當self.collectionView被創建時,它首先調用sizeForItemAtIndexPath,然後調用cellForItemAtIndexPath。這導致我的問題,因爲它只cellForItemAtIndexPath,我通過網絡服務的結果集DetailsCollectionViewCell期間是:

cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"detailsCell" forIndexPath:indexPath]; 
    ((DetailsCollectionViewCell*)cell).details = result; 

DetailsCollectionViewCell擁有的財產細節的制定者,做了一些工作,我需要發生第一次知道正確的細胞大小應該是什麼。

上鍊接的問題,基於上述好像火sizeForItemAtIndexPath後cellForItemAtIndexPath是調用

[self.collectionView.collectionViewLayout invalidateLayout]; 

的唯一方法,但是這在其他問題不適合我,因爲儘管它調用sizeForItemAtIndexPath,並允許工作我從DetailsCollectionViewCell搶到足夠的信息來設置正確的高度不更新用戶界面,直到用戶滾動UICollectionView後,我的猜測是,它有東西從文檔做這一行

在下一個視圖佈局更新週期中發生實際佈局更新。

但是,我很難找到如何解決這個問題。它幾乎感覺就像我需要在DetailsCollectionViewCell上創建一個靜態方法,我可以在第一個sizeForItemAtIndexPath傳遞期間將Web服務結果傳遞給它,然後緩存該結果。但我希望有一個簡單的解決方案,讓UI自動更新。

謝謝,

p.s. - 第一個SO問題,所以希望我遵循所有規則。

回答

2

其實,從我發現,打電話給invalidateLayout會導致調用sizeForItemAtIndexPath所有單元出隊下一單元格時(這是適用於iOS 8.0 <,因爲它8.0將重新計算下一個視圖佈局更新佈局)。

所以我來了,是繼承UICollectionView,並與像這樣重寫layoutSubviews解決方案:

- (void)layoutSubviews 
{ 
    if (self.shouldInvalidateCollectionViewLayout) { 
     [self.collectionViewLayout invalidateLayout]; 
     self.shouldInvalidateCollectionViewLayout = NO; 
    } else { 
     [super layoutSubviews];   
    } 
} 

,然後調用cellForItemAtIndexPathsetNeedsLayout和設置shouldInvalidateCollectionViewLayout爲YES。這適用於iOS> = 7.0。我也通過這種方式實施了估計項目大小。謝謝。

+0

你能在這裏擴展你的答案嗎? '.shouldInvalidateCollectionViewlayout'不是UICollectionView上的屬性? – GarySabo

+0

我已經實現了這一點,但我的單元格仍然只能在滾動收藏視圖後調整大小。想法? –

0

在這裏我的情況和解決方案。

我的collectionView位於scrollView中,我希望我的collectionView和她的單元格能夠在滾動我的scrollView時調整大小。

所以在我的UIScrollView的委託方法:scrollViewDidScroll:

[super scrollViewDidScroll:scrollView]; 

if(scrollView.contentOffset.y>0){ 

    CGRect lc_frame = picturesCollectionView.frame; 
    lc_frame.origin.y=scrollView.contentOffset.y/2; 
    picturesCollectionView.frame = lc_frame; 
} 
else{ 

    CGRect lc_frame = picturesCollectionView.frame; 
    lc_frame.origin.y=scrollView.contentOffset.y; 
    lc_frame.size.height=(3*(contentScrollView.frame.size.width/4))-scrollView.contentOffset.y; 
    picturesCollectionView.frame = lc_frame; 

    picturesCollectionViewFlowLayout.itemSize = CGSizeMake(picturesCollectionView.frame.size.width, picturesCollectionView.frame.size.height); 
    [picturesCollectionViewFlowLayout invalidateLayout]; 
} 

我不得不重新設置collectionViewFlowLayout細胞大小,然後他的無效佈局。 希望它有幫助!

相關問題