![](/img/trans.png)
[英]Center First UICollectionViewCell in UICollectionView
[英]Make UICollectionViewCell appear in center of UICollectionView
我有一些動態添加到UICollectionView
單元格。 我想要做的是更改這些單元格的插入,使它們出現在UICollectionView
的中心。 這是因為添加單元格高度的單元格越多(它是單行UICollectionView
)。
- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
// This method is used to center when one tile is entered else use a standard no inset
if (self.wordArray.count == 1) {
CGFloat newWidth = (self.tileCollectionView.bounds.size.width - self.tileCollectionView.bounds.size.height);
return UIEdgeInsetsMake(0, (newWidth / 2), 0, (newWidth/2));
} else {
return UIEdgeInsetsMake(0, 0, 0, 0); // top, left, bottom, right
}
}
我如何獲得對任何單元格的UICollectionViewCell
當前高度的引用,因為它們的形狀都相同(只有當更多的單元格繼續適合一行時,它們的高度/寬度會發生變化。
一旦我獲得了單元格高度的引用,我可以添加類似:self.tileCollectionView.bounds.size.height - CELLHEIGHT / 2 - 用作單元格的插圖。
如果您的所有單元格大小相同並且假設您使用的是UICollectionViewFlowLayout
,則可以使用它來獲取它們的大小:
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
CGFloat width = flowLayout.itemSize.width;
CGFloat height = flowLayout.itemSize.height;
這是我使用UICollectionViewFlowLayout
計算我的插圖的方法:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
NSInteger numberOfCells = self.view.frame.size.width / flowLayout.itemSize.width;
NSInteger edgeInsets = (self.view.frame.size.width - (numberOfCells * flowLayout.itemSize.width)) / (numberOfCells + 1);
return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets);
}
您還需要確保在屏幕旋轉時使布局無效,以使其再次計算新的插入內容:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self.collectionView.collectionViewLayout invalidateLayout];
}
如果你使用網格式布局,我會嘗試這個方法: collectionView:layout:sizeForItemAtIndexPath:
您需要實現UICollectionViewFlowLayoutDelegate才能執行此操作。 要使它們堆疊,請將最小偏移設置為負數,即單元格本身的大小。 這可能需要一些試驗和錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.