ios – 使用UICollectionViewCell上的按钮显示数组中的数据

我有一系列NSStrings,一个UILabel&一个UICollectionView.

我的问题:

我想要数组的计数来确定有多少UICollectionViewCell.

每个UICollectionViewCell都包含一个按钮.单击后,我希望此按钮使数组中与UICollectionViewCell编号对应的数据显示在标签中.

例如,如果用户单击第13个UICollectionViewCell的按钮,则数组中的第13个NSString将成为UILabel的文本.

我做了什么:

我已经为我用于所有UICollectionViewCells的nib文件创建了自己的UICollectionViewCell子类,&将按钮连接到.h文件作为IBAction.我还导入了MainViewController.h,它包含存储NSStrings的数组属性.

当我在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的子类,则需要创建一个委托,以便在显示数据的viewController中使触摸事件可用.

一个简单的调整是添加collectionViewCell按钮,将它的IBOutlet连接到单元格.但不是IBAction.在cellForRowAtIndexPath中:在包含collectionView的viewController中为按钮添加一个eventHandler.

- (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;

}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...