使用UICollectionViewCell上的button来显示数组中的数据

我有一个NSStrings的数组,一个UILabel和一个UICollectionView

我的问题:

我想要数组的数量来确定有多less个UICollectionViewCell

每个UICollectionViewCell包含一个button。 点击后,我想要这个button,使数组中对应于UICollectionViewCell编号的数据显示在标签中。

例如,如果用户点击第十三个UICollectionViewCell的button,那么数组中的第十三个NSString将成为UILabel的文本。

我做了什么:

我为UICollectionViewCell创build了自己的子类,用于所有UICollectionViewCell的nib文件, UICollectionViewCell该button作为IBAction连接到.h文件。 我还导入了MainViewController.h ,它是包含存储NSString的数组属性的MainViewController.h

当我编辑UICollectionViewCell的操作中的代码时,我无法访问数组属性。 button确实有效 – 我把NSLog放在了IBAction的方法中,它可以工作。

我已经search了其他几十个答案,但没有回答我的具体问题。 如果需要,我可以用我的代码样本更新这个。

我已经为我用于所有UICollectionViewCells的nib文件创build了自己的UICollectionViewCell的子类,并将该button连接到.h文件作为IBAction。

如果将IBAction连接到collectionViewCell的子类,则需要创build一个委托,使触发事件在显示数据的viewController中可用。

一个简单的调整是添加buttonViewCell的button,将它的IBOutlet连接到单元格。 但不是IBAction。 在cellForRowAtIndexPath:为包含collectionView的viewController中的button添加一个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; } 

请尝试像这样

在YourCollectionViewCell.h中

为添加到xib的UIButton创build一个名为IBOut而不是IBAction的button。 请记住,您应该将sockets连接到单元对象而不是xib中的文件所有者。

MainViewController.m

  - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { cell.button.tag = indexPath.row; [cell.button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; return cell; } -(void)buttonPressed:(UIButton*)sender { NSLog(@"%d : %@",sender.tag,[array objectAtIndex:sender.tag]); self.textLabel.text = [array objectAtIndex:sender.tag]; } 

编辑 – 处理多个部分

  -(void)buttonPressed:(UIButton*)sender { NSIndexPath *indexPath = [self.collectionView indexPathForCell: (UICollectionViewCell *)sender.superview.superview]; NSLog(@"Section : %d Row: %d",indexPath.section,indexPath.row); if (0 == indexPath.section) { self.textLabel.text = [firstArray objectAtIndex:indexPath.row]; } else if(1 == indexPath.section) { self.textLabel.text = [secondArray objectAtIndex:indexPath.row]; } } 

当我编辑UICollectionViewCell的操作中的代码时,我无法访问数组属性。

那是因为你把button动作连接到了“错误”的对象。 它需要被连接到MainViewController(或者那些可以访问数组属性的人)。

你将要执行几个任务:

  • 接收button动作消息。

  • 访问数组(数据的模型 )。

  • 抛出一个开关,指出哪个单元现在应该显示其标签。

  • 告诉集合视图reloadData ,从而刷新单元格。

所有这些任务应该最方便地属于一个对象。 我假设这是MainViewController(因此我假定MainViewController是集合视图的委托/数据源)。