ios - UICollectionView 标题重叠

标签 ios objective-c uicollectionview uicollectionviewcell uicollectionviewlayout

我有一个带有以下相关方法的collectionView:

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

    if (kind == UICollectionElementKindSectionHeader) {
    Scoreboard *thisScoreboard = [self.scoreboards objectAtIndex:indexPath.section];

    ScoreboardReusableView *view = nil;

    view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                              withReuseIdentifier:@"scoreboardHeader"
                                                     forIndexPath:indexPath];

    //view.backgroundColor = [UIColor yellowColor];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    //label.text = [NSString stringWithFormat:@"%@ vs %@", thisScoreboard.awayteam, thisScoreboard.hometeam];
    label.text = [NSString stringWithFormat:@"%ld", (long)indexPath.section];


    [view addSubview:label];

    return view;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 34);
}

但是,标签文本重叠。这是collectionView的两个屏幕截图。第 0 部分和第 1 部分(注意文本如何不重叠):

enter image description here

第 2 节和第 3 节(文本在此处以及所有后续节标题上重叠): enter image description here

我的标题 xib ScoreboardReusableView 完全空白,因为无论我在其中放入什么(例如 UILabel 或 UIImageView,它都不会显示在 UICollectionView 标题中)。我最好在 xib 中设计 header ,但由于这不起作用,我尝试以编程方式完成它,但现在标签重叠。

最佳答案

Collection View 重复使用单元格和标题。当标题滚动到屏幕外时,它会被添加到队列中,并将重新用于下一个要在屏幕上滚动的标题。这意味着 collectionView:viewForSupplementaryElementOfKind: 方法中的配置代码将在不同 indexPaths 的同一 header View 上再次运行。由于您只是在每次运行配置代码时添加一个标签,因此它们会将一个标签堆叠在另一个之上。

正确的做法是在headerView上有一个label属性,这样它的文本就可以改变。但是...

no matter what I put in it (e.g., a UILabel or a UIImageView), it would not show up

这是你真正的问题。您在 xib 上启用了自动布局吗?如果是这样,请务必为标签添加约束,否则它将具有零宽度和高度,从而产生您所描述的效果。

关于ios - UICollectionView 标题重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580512/

相关文章:

ios - spritekit 中的颜色不匹配

objective-c - 捕获对象上的所有方法/消息调用

ios - 获取索引路径 如果用户在 UITableview 中编辑 UITextfield

ios - 在 .xib 中创建的 UICollectionView 是 nil Swift

android - 我们如何在 flutter_riverpod 中没有 ref 对象的情况下访问提供程序?

ios - 推送通知导致应用程序崩溃

Javascript 日期/时间不适用于带有 Chrome 的 iOS 设备

ios - 为什么我没有得到 NSString 的输出

ios - 显示我从 JSON 获得的数据

ios - 在加载之前为所有索引调用 sizeForItemAtIndexPath - 我很确定我遇到了 UICollectionView 错误或糟糕的设计