gpt4 book ai didi

ios - UICollectionView 中的单元格重叠

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:38 25 4
gpt4 key购买 nike

我正在使用一个 ViewController,我在其中添加了一个 UICollectionView:

UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[collectionViewFlowLayout setMinimumInteritemSpacing:2];
[collectionViewFlowLayout setMinimumLineSpacing:4];
[collectionViewFlowLayout setHeaderReferenceSize:CGSizeMake(320, 30)];

CGRect collectionViewFrame = self.view.bounds;
self.collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:collectionViewFlowLayout];
self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

self.collectionView.delegate = self;
self.collectionView.dataSource = self;

[self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:myCellIdentifier];

[self.view addSubview:self.collectionView];

这就是我初始化自定义单元格对象的方式(我确保每个单元格的框架填满屏幕的整个宽度,以便单元格在 UICollectionView 中一个接一个地垂直呈现):

CGSize mySize = CGSizeMake(320, 158);
self.myTitle = [[UILabel alloc ] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
[self.myTitle setTextColor:[UIColor whiteColor]];
[self.myTitle setBackgroundColor:[UIColor greenColor]];
[self.myTitle setTextAlignment:NSTextAlignmentLeft];
[self.myTitle setNumberOfLines:1];
[self.myTitle setText:@"My Title"];
[self addSubview:self.myTitle];

这就是我在 initWithNibName 中初始化单元格框架的方式:

CGSize mySize = CGSizeMake(320, 158);
self = [super initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];

这是我的 cellForItemAtIndexPath 代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:myCellIdentifier forIndexPath:indexPath];

return cell;
}

现在我有四个这样的单元格,但它们是重叠的。我究竟做错了什么?谢谢!

最佳答案

实现 UICollectionViewFlowLayout 委托(delegate)调用:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(320, 158);
}

或者由于所有尺寸都是恒定的,只需像这样在 Flow 布局中指定尺寸:

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.itemSize = CGSizeMake(320, 158);

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

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