Handling multiple UISwitch controls in a table view without using tag property

后端 未结 4 778
-上瘾入骨i
-上瘾入骨i 2020-12-19 09:34

I have a table view controller with multiple UISwitch controls in them. I set the delegate to the table view controller with the same action for all switches. I need to be a

4条回答
  •  攒了一身酷
    2020-12-19 10:01

    I realize I'm about three years late to the party but I've developed a solution without subclassing that I think is preferable (and simpler). I'm working with the exact same scenario as Thaurin's described scenario.

    - (void)toggleSwitch:(id) sender
    {
        // declare the switch by its type based on the sender element
        UISwitch *switchIsPressed = (UISwitch *)sender;
        // get the indexPath of the cell containing the switch
        NSIndexPath *indexPath = [self indexPathForCellContainingView:switchIsPressed];
        // look up the value of the item that is referenced by the switch - this
        // is from my datasource for the table view
        NSString *elementId = [dataSourceArray objectAtIndex:indexPath.row];
    }
    

    Then you want to declare the method shown above, indexPathForCellContainingView. This is a seemingly needless method because it would appear at first glance that all you have to do is identify the switch's superview but there is a difference between the superviews of ios7 and earlier versions, so this handles all:

    - (NSIndexPath *)indexPathForCellContainingView:(UIView *)view {
        while (view != nil) {
            if ([view isKindOfClass:[UITableViewCell class]]) {
                return [self.myTableView indexPathForCell:(UITableViewCell *)view];
            } else {
                view = [view superview];
            }
        }   
        return nil;
    }
    

提交回复
热议问题