[英]How to center the first and the last cell of a horizontal UICollectionView?
我試圖將水平集合視圖的第一個和最后一個單元格居中。
我發現的唯一方法是在我的UICollectionView
的開頭和結尾添加額外的單元格。 出於顯而易見的原因,這種方法完全不是一個壞主意,但我現在還沒有找到更好的方法。 而且,由於iPhone 6和iPhone 6+,我的視圖布局完全被破壞了......(facepalm)
為了說明我的需要,我需要顯示如下內容:
| x x x x x| where the first x represent my first cell
and
|x x x x x | where the last x represent my last cell
我認為使用UICollectionViewFlowLayout
子類是使用contentInset
東西的正確方法,但我是這些組件的新手。
有關如何實現此目的的任何鏈接或建議?
發布在這里供將來參考,因為我一直在處理同樣的問題,並找到了解決方案。 使用Swift 3在Xcode版本8.2.1(8C1002)中測試
UICollectionViewDelegate具有func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
要使集合視圖中的第一個和最后一個單元格居中,您可以通過以下方式計算插入:
let inset: CGFloat = collectionView.frame.width * 0.5 - cellSize.width * 0.5
在此之后,您只需返回新的UIEdgeInsetMake(0, inset, 0, inset)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let inset: CGFloat = collectionView.frame.width * 0.5 - cellSize.width * 0.5
return UIEdgeInsetsMake(0, inset, 0, inset)
}
------- 編輯 -------
在這種情況下,我將單元格大小存儲為硬編碼值,並使用委托func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
易於處理您的不同部分。
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, collectionView.frame.size.width/2, 0, collectionView.frame.size.width/2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.