在集合视图中为UI开关编写事件

嗨,我正试图编写UI集合视图中的UI切换和UI分段控制的事件。

我在collection视图单元格中声明了UIswitch和UIsegmentation控件。

@interface CollectionViewCell:UICollectionViewCell

@property (strong, nonatomic) IBOutlet UISegmentedControl *mySegmentedControl; @property (strong, nonatomic) IBOutlet UISwitch *Myswitch; 

并从视图controller.m访问它

 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath]; if(cell.Myswitch.isOn) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"!Alert" message:@"Do you want to exit the application?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show]; } else { } } 

但是UI切换和分割控制都不适合我。 任何帮助将不胜感激。

不要使用

 CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath]; 

didSelectItemAtIndexPath因为它会出列一个新的空的CollectionViewCelldequeueReusableCellWithReuseIdentifier实际上只应在cellForItemAtIndexPathcellForItemAtIndexPath

如果你想访问给定索引path的单元格说

 CollectionViewCell *cell = [collectionView cellForItemAtIndexPath: indexPath]; 
  1. 使用addTarget:action:forControlEvents: cellForItemAtIndexPath :在cellForItemAtIndexPath方法中的方法中:
 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; cell.mySwitch.tag = indexPath.row; [cell.mySwitch addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged]; //another cell setup code return cell; } 
  1. 实现callback方法
 - (void) switchValueChanged: (UISwitch *) sender { NSInteger index = sender.tag; //your code } 
  1. didSelectItemAtIndexPath删除该代码