4

我希望能够在 UICollectionView 中设置内容大小的最小高度,这样我就可以隐藏/显示 UISearchbar,类似于在 iBooks 上完成的方式。

但是,我不想对布局进行子类化,因为我想为 UICollectionView 保留标准的垂直布局。

有任何想法吗?

4

3 回答 3

8

您可以通过继承 UICollectionViewFlowLayout 并覆盖该方法来做到这一点

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

编辑:我刚刚意识到你说你不想继承布局。无论如何,我继承了 UICollectionViewFlowLayout 并且只修改了 collectionViewContentSize 方法。它为我保留了标准的垂直布局。

编辑:https ://stackoverflow.com/a/14465485/2017159 。这里说 UICollectionViewFlowLayout 只支持一个方向(垂直或水平),所以应该没问题吧?

于 2013-06-19T18:39:37.750 回答
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/header 视图。

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

补充视图教程techotopia.com , appcode.com , mobinius

于 2013-04-10T09:21:34.170 回答
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;
}
于 2013-10-09T15:18:05.440 回答