在顶部显示节标题,UICollectionViewFlowLayout滚动设置为水平

时间:2014-07-30 08:55:22

标签: ios uicollectionview uicollectionviewlayout

这是this question的副本。我再次提问,因为接受的答案不起作用,没有人提供更多关于假设正确答案如何运作的解释。

所以在这种情况下:我想将集合视图显示在一行中。为此,我将自定义UICollectionViewFlowLayout应用于集合视图,并将滚动设置为水平。一切都运行正常,除了标题标题消失了。

Header disappeared

为了解决这个问题,我实现了这个功能:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section 
  {
    return CGSizeMake(350, 35);
  }

现在显示标题,但问题是它显示在单元格的左侧,而不是通常的顶部。

我在寻找解决方案时偶然发现了上面的链接,但就像我说的那样,接受的答案根本不起作用,我无法找到关于这种情况的其他解决方案。所以有人可以帮助我吗?

Wrong header position

2 个答案:

答案 0 :(得分:1)

我们可以通过使用委托方法 -

来做到这一点
(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

并保持左侧插入补充视图宽度的负值并管理顶部插入

答案 1 :(得分:-1)

您是否尝试使用此类标题?

首先:在viewDidLoad中设置......

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.headerReferenceSize = CGSizeMake(self.collectionView.bounds.size.width, 30);
// add any other setup you need
[self.collectionView setCollectionViewLayout:flowLayout];

第二:添加标题视图...

#define LABEL_TAG 128

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                            UICollectionElementKindSectionHeader withReuseIdentifier:@"SectionHeader" forIndexPath:indexPath];
    UILabel *label = (UILabel *)[headerView viewWithTag:LABEL_TAG];
    if (!label) {
        label = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 5, 5)];
        label.tag = MY_HEADER_LABEL_TAG;
        label.font = [UIFont boldSystemFontOfSize:12];
        label.textColor = [UIColor redColor];
        [headerView addSubview:label];
    }

    label.text = [NSString stringWithFormat:@"Section %d", indexPath.section];
    return headerView;
}