ios - 无法获取第一个单元格的正确索引

标签 ios objective-c uicollectionview

尝试从 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];

关于ios - 无法获取第一个单元格的正确索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47178810/

相关文章:

iphone - 如何在 didSelectRowAtIndexPath 中到达当前选定的单元格?

ios - 在运行时更改 Collection View 单元格宽度

ios - Swift - 为 UICollectionViewCell 选择图像和标签

ios - UIButton 的 .touchUpInside 事件不起作用

objective-c - 动画 UIView 框架, subview UIScrollView 并不总是动画

iphone - 即时更改 iOS 应用程序的语言

ios - 如何在 WatchOS 的基于页面的界面中显示警报?

iphone - UITableView 部分索引与搜索栏重叠

java - 将 JSON 数据从 iOS 发布到 java Web 服务

ios - initWithCoder : and initWithFrame: 之间共享初始化方法的命名约定