2013-04-03 60 views
4

我希望能夠在UICollectionView中設置內容大小的最小高度,所以我可以隱藏/顯示UISearchbar,類似於在iBooks上完成的方式。設置UICollectionView的最小內容大小

但是,我不想爲繼承UICollectionView的標準垂直佈局而繼承佈局。

有什麼想法?

回答

0

你可以試試這個快速解決方案,如果你有足夠的物品填滿屏幕,搜索欄將被隱藏。當然,您可以使用任何自定義視圖更改下面的UISearchBar。

collectionView.contentInset = UIEdgeInsetsMake(44.0, 0.0, 0.0, 0); 
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, -44, collectionView.frame.size.width, 44)]; 
[collectionView addSubview:searchBar]; 
if([items count] != 0){ 
    [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO]; 
} 

完全相同的另一個解決方案是使用補充視圖。我剛剛走了。創建UICollectionReusableView的子類,請確保您設置頁眉參考尺寸的流佈局

[flowLayout setHeaderReferenceSize:CGSizeMake(0, 44.0)]; 

註冊集合視圖

[playersCollectionView registerClass:[MySupplementaryView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyHeader"]; 

的補充視圖和執行UICollectioViewDataSource方法

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 
{ 
    MySupplementaryView *header = nil; 

    if ([kind isEqual:UICollectionElementKindSectionHeader]){ 
     header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyHeader" forIndexPath:indexPath]; 
     header.headerLabel.text = @"bla bla"; 
    } 
    return header; 
} 

最後,在每次重新加載後,在第一個項目的開始處重新定位收集視圖以隱藏searchBar /標題視圖。

if([items count] != 0){ 
    [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO]; 
} 

教程補充意見techotopia.comappcode.commobinius

8

您可以通過繼承UICollectionViewFlowLayout和覆蓋方法

-(CGSize)collectionViewContentSize 
{ //Get the collectionViewContentSize 
    CGSize size = [super collectionViewContentSize]; 
    if (size < minimumSize) return minimumSize; 
    else return size; 
} 

編輯做到這一點: 我才意識到,你說你不想要佈局的子類。無論如何,我subclassed UICollectionViewFlowLayout並只修改collectionViewContentSize方法。它爲我保留了標準的垂直佈局。編號:https://stackoverflow.com/a/14465485/2017159。這裏說它UICollectionViewFlowLayout只支持一個方向(垂直或水平),所以它應該很好?

+0

令人驚歎:)感謝您的回答! –

0

這是khangsile的答案的調整版本。 僅加蓋實際上小於最小尺寸的尺寸

- (CGSize)collectionViewContentSize 
{ 
    CGSize size = [super collectionViewContentSize]; 

    size.width = MAX(size.width, self.minimumContentSize.width); 
    size.height = MAX(size.height, self.minimumContentSize.height); 

    return size; 
}