ios - UICollectionView indexPath.row 或项目,项目不稳定,跳来跳去

标签 ios objective-c uicollectionview uicollectionviewcell uicollectionviewlayout

我创建了一个 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/

相关文章:

ios - Xcode 5.1 : Where have the delta iOS 6/7 settings gone?

ios - 由于最大应用程序 ID 限制,无法调试我的应用程序

ios - AFNetworking 1.x 的 SSL 固定

ios - 在 ios 上分配属性会发生什么

objective-c - 为什么 == 对具有相同值的 NSNumber 返回 true?

ios - 如何在 Objective-C 中将对象类型转换为另一个类

swift - UICollectionView 自动调整大小和动态行数

ios - 在 TableView 中的 Collection View 中同步滚动动画

ios - 当 Webview 在 Collection View 单元格中时,如何检测 UIWebView 何时开始加载?

ios - 通过 LAN 在 Lightroom 插件和 iOS 应用程序之间进行通信