UICollectionView indexPath.row或item,项目不稳定,跳转

den*_*kov 3 objective-c ios uicollectionview uicollectionviewcell uicollectionviewlayout

我创建了一个集合视图,我正在将图像加载到其中.问题我正在运行的是当我点击一个单元格来获取它的indexPath.item或indexPath.row时,数字都被搞砸了.单击第一个图像不显示任何内容,单击下一个图像将给我0.点击第三个将给我1,然后单击第二个给我一个2.这在整个视图中都会发生.我必须做错事.这是我的代码:

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];
Run Code Online (Sandbox Code Playgroud)

委托方法:

- (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);
}
Run Code Online (Sandbox Code Playgroud)

我不确定如何准确控制到底发生了什么.它们的编号通常如下:

0 1 2
3 4 5
....
Run Code Online (Sandbox Code Playgroud)

或者有一种特殊的方式,他们根据部分编号?他们如何填充?

Mar*_*n R 9

你已经实现了didDeselectItemAtIndexPath:,而不是didSelectItemAtIndexPath:.因此,选择单元格会记录先前所选单元格的索引路径.