我有一组 NSStrings
,一个 UILabel
和一个 UICollectionView
。
我的问题:
我想要数组的计数来确定有多少 UICollectionViewCell
。
每个 UICollectionViewCell
都包含一个按钮。单击后,我希望此按钮使与 UICollectionViewCell
的编号对应的数组中的数据显示在标签中。
例如,如果用户点击第 13 个 UICollectionViewCell
的按钮,那么数组中的第 13 个 NSString
将成为 UILabel
的文字。
我做了什么:
我为我用于所有 UICollectionViewCell
的 nib 文件创建了自己的 UICollectionViewCell
子类,并将按钮连接到 .h 文件作为IBAction
。我还导入了 MainViewController.h
,它包含存储 NSString
的数组属性。
当我在 UICollectionViewCell
的操作中编辑代码时,我无法访问数组属性。该按钮确实有效 - 我在 IBAction
的方法中放置了一个 NSLog,它确实有效。
我在 SO 上搜索了数十个其他答案,但没有一个能回答我的具体问题。如果需要,我可以用我的代码示例更新它。
最佳答案
I have made my own subclass of UICollectionViewCell for the nib file that I use for all of the UICollectionViewCells, and connected the button to the .h file as a IBAction.
如果将 IBAction 连接到 collectionViewCell 的子类,则需要创建一个委托(delegate),使触摸事件在显示数据的 viewController 中可用。
一个简单的调整是添加按钮 collectionViewCell,将它的 IBOutlet 连接到单元格。但不是 IBAction。在 cellForRowAtIndexPath:
中,为包含 collectionView 的 viewController 中的按钮添加一个事件处理程序。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//Dequeue your cell
[cell.button addTarget:self
action:@selector(collectionViewCellButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (IBAction)collectionViewCellButtonPressed:(UIButton *)button{
//Acccess the cell
UICollectionViewCell *cell = button.superView.superView;
NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
NSString *title = self.strings[indexPath.row];
self.someLabel.text = title;
}
关于ios - 使用 UICollectionViewCell 上的按钮显示数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16453205/