我创建了一个 Collection View 并将图像加载到其中。我遇到的问题是当我单击一个单元格以获取它的 indexPath.item 或 indexPath.row 时,数字都搞砸了。单击第一张图片不显示任何内容,单击下一张将给我 0。单击第三张将给我一个 1,然后再单击第二张将给我一个 2。整个 View 都会发生这种情况。我做的一定是错的。这是我的代码:
viewDidLoad:
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);
[layout setItemSize:CGSizeMake(75, 75)];
self.images = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 230, self.view.frame.size.width, 200) collectionViewLayout:layout];
self.images.delegate = self;
self.images.dataSource = self;
[self.images registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.view addSubview:self.images];
委托(delegate)方法:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.imagesGallery.count; //image paths for server
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.layer.borderWidth = 1;
cell.layer.borderColor = [[UIColor whiteColor]CGColor];
UIImageView *image = [[UIImageView alloc]init];
image.image = [UIImage imageWithData:[self.imagesGallery objectAtIndex:indexPath.row]];
image.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
[cell addSubview:image];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%d", indexPath.item);
}
我不确定如何准确控制内容的去向。它们的编号是否正常:
0 1 2
3 4 5
....
或者是否有一种特殊的方法可以根据部分对它们进行编号?它们是如何填充的?
最佳答案
您已经实现了 didDeselectItemAtIndexPath:
,而不是 didSelectItemAtIndexPath:
。
因此,选择一个单元格会记录先前所选单元格的索引路径。
关于ios - UICollectionView indexPath.row 或项目,项目不稳定,跳来跳去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23252489/