iOS UICollectionView如何通过编程的方式移除头部视图

6

我希望能够控制UICollectionView的头部,因为我需要根据用户生成的事件来删除和添加它。

目前为止,我尝试过以下方法:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

    if(toRemoveHeader){

        return CGSizeZero;

    }else{

        return CGSizeMake(320, 45);

    }
}

当用户事件被触发时,您可以调用[self.collectionView reloadData]。但是,我希望在不重新加载数据的情况下实现此功能。您有什么想法吗?

嗨!你是怎么解决这个问题的?=D - Adriano Tadao
我不认为我解决了它... - Petar
2个回答

5
如果您正在使用Swift,您可以在UICollectionViewController子类中这样做:
var hideHeader: Bool = true //or false to not hide the header

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    if hideHeader {
        return CGSizeZero //supplementary view will not be displayed if height/width are 0
    } else {
        return CGSizeMake(30,80) //size of your UICollectionReusableView
    }
}

如果您想获取在Storyboard中指定的header视图的现有大小,请将CGSizeMake(30,80)行替换为以下内容:let headerView = self.view.subviews[0].subviews[0] as! UICollectionReusableView let existingSize = headerView.frame.size return existingSize - gammachill

2
您的实现已经完全可用,问题可能在于您没有将实现该函数的对象分配给collectionViewdelegate属性。
函数collectionView:layout:referenceSizeForHeaderInSection:由确认UICollectionViewDelegateFlowLayout协议的类实现,并且collectionView期望其delegate实现此方法,而不是dataSource
在我的某个实现中,仅当该
中没有单元格时才显示
,只要正确设置了delegate属性,它就可以完美地工作。
#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize) collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForFooterInSection:(NSInteger)section
{
    NSUInteger count = [self collectionView: collectionView
                     numberOfItemsInSection: section];
    CGFloat footerHeight = (count == 0) ? 60.f : 0.f;
    CGFloat footerWidth = collectionView.frame.size.width;
    return CGSizeMake(footerWidth, footerHeight);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接