writing events for UIswitch in collection view

2019-02-27 07:35发布

问题:

Hi I am trying to write events for UI switch and UI segmentation control in UI collection view.

I declared the UIswitch and UIsegmentation control in collection view cell.

@interface CollectionViewCell : UICollectionViewCell

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

and access it from view 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
{

}
}

But UI switch and segmentation control both not works for me. Any help will be appreciated.

回答1:

  1. Use addTarget:action:forControlEvents: in method in cellForItemAtIndexPath method:

- (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. Implement callback method:

- (void) switchValueChanged: (UISwitch *) sender {
    NSInteger index = sender.tag;
    //your code
}
  1. Remove that code from didSelectItemAtIndexPath


回答2:

Don't use

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

in didSelectItemAtIndexPath as it will dequeue a new empty CollectionViewCell. dequeueReusableCellWithReuseIdentifier should really only be called in cellForItemAtIndexPath.

If you want to access the cell for a given index path say

CollectionViewCell *cell = [collectionView cellForItemAtIndexPath: indexPath];