How to disable UITableViewCell, but still have interactions with accessories (e.g. UISwitch)

Is there a way to disable the UITableViewCell from starting the didSelectCellAtIndexPath: delegate, while still maintaining the ability to use the UISwitch, which is in an additional view of this cell.

I know that you can set cell.userInteractionEnabled = NO, this will disable the cell, but also does not allow me to use the switch in the accessory. I know that I could also try to determine which cell was used in the didSelectCellAtIndexPath: method, but since my table view is dynamic and changes depending on what the user is doing, this can become messy.

I am looking for a simple and elegant solution that I could use. Any ideas?

+6
source share
2 answers

if you do not want to use cell.userInteractionEnabled = NO then you set cell.selectionStyle = UITableViewCellSelectionStyleNone

and let your cell trigger do a SelectRowAtIndexPath.

Now in this “didSelectRowAtIndexPath” method, you need to avoid / ignore the selection by comparing the type of the object with the data array at that particular index.

+7
source

Add an event listener directly to UISwitch instead of relying on didSelectRowAtIndexPath .

 -(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { // Here I assume you created a subclass MyCell of UITableViewCell // And exposed a member named 'switch' that points to your UISwitch MyCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; if (cell == nil) { cell = [[MyCell alloc] init]; cell.selectionStyle = UITableViewCellSelectionStyleNone; // This could be moved into MyCell class [cell.switch addTarget:self action:@selector(switchChanged:) forControlEvent:UIControlEventValueChanged]; } // Now we need some way to know which cell is associated with the switch cell.switch.tag = indexPath.row; } 

Now, to listen for swich events, add this method to the same class

 -(void)switchChanged:(UISwitch*)switch { NSUInteger cellIndex = switch.tag; ... } 
0
source

Source: https://habr.com/ru/post/947905/


All Articles