12

如何使用自動佈局更改基於子視圖大小的UICollectionViewCell的大小?如何使UICollectionViewCell適合其子視圖(使用自動佈局)

我的UICollectionViewCell每個只在他們的contentView有一個視圖。這是我的一個自定義UIView子類,可以使用自動佈局自動調整其大小以適合其所有子視圖。它也正確實施了-intrinsicContentSize。然而,UICollectionView,或者說它的佈局,似乎並不關心這一點。

我使用的是UICollectionViewFlowLayout,並嘗試:

  • 離開itemSize其默認值。這使我的單元格大小爲50 x 50.
  • 實施委託方法-collectionView:layout:sizeForItemAtIndexPath:。但是,當調用此方法時,單元格(顯然)尚未出現在屏幕上,並且尚未由Auto Layout系統更新。

有什麼方法可以根據使用標準Apple類的子視圖更改單元格大小?或者我是否必須實現我自己的UICollectionViewLayout子類,或其他?

+0

原理相同http://stackoverflow.com/questions/18477220/have-uitableviewcell-resize-itself-with-autolayout/18481179#18481179,不幸的是,您需要預先給出尺寸。 – jrturton

+1

上面的作者在使用「自由」單元格時有一個評論 - 您創建一個然後保持周圍,以填充並獲取大小。你應該能夠使用[單元systemLayoutSizeFittingSize:UILayoutFittingCompressedSize] - 我現在有問題,但其中的一個應該工作。 –

回答

-2

嘗試的CollectionView:佈局:sizeForItemAtIndexPath:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { 
    return self.view.frame.size; 
} 
0

我用

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { 

    if (indexPath.row == 0) { 
     UIButton *button = (UIButton *)[cell viewWithTag:2]; 
     CGRect frame = cell.frame; 
     frame.size.width = button.frame.size.width; 
     cell.frame = frame; 
    } 

} 

,並能夠根據按鈕子視圖在一個小的測試應用程序的寬度來調整我的手機。

請確保您的子視圖上的標籤大於0,因爲如果您使用0,它只會讓您回到contentView。除此之外,這應該讓你有

1

你有沒有嘗試過這樣的:

[self.view layoutIfNeeded]; 
[UIView animateWithDuration:0.5 animations:^{ 
    constraintConstantForWidth.constant = subviews.size.width; 
    constraintConstantForHeight.constant = subviews.size.height; 
    [self.view layoutIfNeeded]; 
}]; 

,使約束的優先級(低= 250)

我認爲,這個問題我們可以通過處理約束不變的替換。

相關問題