尝试从 didSelectItemAtIndexPath 中的cellForItemAtIndexPath
访问uilabel
,但无法获取第一个单元格。 这是我的代码
在cellForItemAtIndexPath
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UILabel *featureName = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, cell.frame.size.width-10, cell.frame.size.height-10)];
featureName.tag = indexPath.row;
[cell addSubview:featureName];
在didSelectItemAtIndexPath
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
UILabel *featureName = [cell viewWithTag:indexPath.row];
featureName.textColor = [UIColor lightGrayColor];
可以从所有单元格中获取label.tag
,但不能从第一个单元格中获取。点击第一个单元格时应用程序崩溃。
第一
行的indexPath.row
为 0,但 0 不是有效的标记。我认为您应该只使用非零值。
尝试即
featureName.tag = indexPath.row + 1;
...
UILabel *featureName = [cell viewWithTag:indexPath.row+1];
cellForItemAtIndexPath
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UILabel *featureName = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, cell.frame.size.width-10, cell.frame.size.height-10)];
featureName.tag = indexPath.row + 1;
[cell addSubview:featureName];
in didSelectItemAtIndexPath
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
UILabel *featureName = [cell viewWithTag:indexPath.row + 1 ];
featureName.textColor = [UIColor lightGrayColor];
希望这能解决您的问题:)