UICollectionView 显示错误的单元格选择问题

UICollectionView shows wrong cell selected issue

我有一个 CollectionView 有很多细胞。一旦我 select 其中一个都显示相同的名称,但是当我滚动时,我再次得到所有名称不同但都相同的单元格。所以每个卷轴给我不同的名字,但都有相同的名字。那么请问我的问题在哪里?

我检查过这个 UICollectionView showing wrong cells after scrolling - dequeue issue? 但它对我没有帮助。

顺便说一句,我有一个 tableView 并且工作正常。

更新问题: 我如何调用 didSelectItemAtIndexPath 之外的选定单元格标签 FOR UICollectionView?

解决方案:

NSIndexPath *path2 = [[_collection indexPathsForSelectedItems] lastObject];
ProductsCollectionViewCell *cell2 = (ProductsCollectionViewCell *) [_collection cellForItemAtIndexPath:path2];

我就是这样做的。

////////////////////////////////////////// //

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

self.lblCollectionId = nil;
self.lblCollection = nil;

static NSString *identifier = @"cell";

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

_lblCollection = (UILabel *)[cell viewWithTag:102];
_lblCollection.text = [_arraySubCategory objectAtIndex:indexPath.row];

_lblCollectionId = (UILabel *)[cell.contentView viewWithTag:101];
_lblCollectionId.text = [_arrayID objectAtIndex:indexPath.row];

_imgCollection = (UIImageView *)[cell.contentView viewWithTag:100];

[_imgCollection sd_setImageWithURL:[NSURL URLWithString:[_arrayImage objectAtIndex:indexPath.row]]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *path = [_tbl indexPathForSelectedRow];
    ProductsTableViewCell *cell = (ProductsTableViewCell *) [_tbl cellForRowAtIndexPath:path];
    _selectedID = cell.lblID.text;

    _selectedIDCollection = _lblCollectionId.text;
    NSLong(@"%@ Selected", _selectedIDCollection);
}

IAS 更新:

static NSString *simpleTableIdentifier = @"proCell";
ProductsCollectionViewCell *proCell = [_collection dequeueReusableCellWithReuseIdentifier:simpleTableIdentifier forIndexPath:indexPath];

proCell.lblProduct.text = [_arraySubCategory objectAtIndex:indexPath.row];
proCell.lblID.text = [_arrayID objectAtIndex:indexPath.row];

使用标签是一个非常糟糕的主意,尤其是在这里,因为您在原型单元格上定义了标签,因此每个单元格都相同。 您必须使用 IBOutlet 创建自定义 collectionViewCell class 和 link 标签和 imageView,以便您可以正常访问它们:

CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.label1.text = [_arraySubCategory objectAtIndex:indexPath.row];
cell.label2.text = [_arrayID objectAtIndex:indexPath.row];

检查 this tutorial,它会逐步说明您应该如何操作。