gpt4 book ai didi

ios - UICollectionView 标题重叠

转载 作者:行者123 更新时间:2023-11-29 10:29:09 26 4
gpt4 key购买 nike

我有一个带有以下相关方法的 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 的相同标题 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com