2013-03-01 22 views
6

如何在uicollectionview中實現標頭?我知道你可以添加補充視圖,但我不知道如何讓它們在像uitableview中的標題那樣的部分上面「漂浮」。UICollectionView頂部和側面的浮動標頭

這是我的情況:我有一個與網格格式佈局的單元格的集合視圖。您可以水平和垂直滾動。我想在頂部有一個標題,這樣當您水平滾動時,它會與它水平滾動,但不會垂直滾動。我也想要在左邊垂直滾動collectionview但不水平的同類事物。用補充觀點來實現這一點是否正確?

我正在尋找的最終功能類似於iOS上Numbers電子表格應用程序的功能。

在此先感謝您的幫助!

回答

19

更新:

let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout 
flow.sectionHeadersPinToVisibleBounds = true 

把它傳遞。

+0

快速,簡單。這是比在UITableView中選擇分組/平原更好的選擇。謝謝你,先生。 – NSGangster 2016-10-27 23:27:20

+0

你太棒了!真棒! – deepax11 2017-01-08 22:29:43

9

編輯:正如在評論中提到的,這個答案是有效的,但不適用於多個部分。看到這個博客的一個更好的解決方案:http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using#notes


您需要指定您的佈局行爲:

爲iOS9
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 
{ 
    NSMutableArray* attributesArray = [[super layoutAttributesForElementsInRect:rect] mutableCopy]; 

    BOOL headerVisible = NO; 

    for (UICollectionViewLayoutAttributes *attributes in attributesArray) { 
    if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) { 
     headerVisible = YES; 
     attributes.frame = CGRectMake(self.collectionView.contentOffset.x, 0, self.headerReferenceSize.width, self.headerReferenceSize.height); 
     attributes.alpha = HEADER_ALPHA; 
     attributes.zIndex = 2; 
    } 
    } 

    if (!headerVisible) { 
    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader 
                         atIndexPath:[NSIndexPath 
                            indexPathForItem:0 
                            inSection:0]]; 
    [attributesArray addObject:attributes]; 
    } 

    return attributesArray; 
} 
+0

因此,將幀的x-原點設置爲「self.collectionView.contentOffset.x」將使它保持連接到視圖框架的一側?非常感謝答案! – 2013-03-01 15:23:52

+0

在這種情況下,這對x軸是正確的。對於你的場景,你需要複製一個跟在Y軸後的第二個頭。 – 2013-03-01 15:31:13

+0

這是一種破舊的黑客攻擊,僅適用於頭部僅用於第一部分的集合視圖。 – 2013-12-26 14:00:10

相關問題