writing events for UIswitch in collection view

試著忘記壹切 提交于 2019-12-31 03:07:10

问题


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


来源:https://stackoverflow.com/questions/40230030/writing-events-for-uiswitch-in-collection-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!