我有一个带有以下相关方法的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 部分(注意文本如何不重叠):
第 2 节和第 3 节(文本在此处以及所有后续节标题上重叠):
我的标题 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/