5

I'm adding a switch to contentView, and the contentView belongs to the cell. I'm trying to get the row number of the cell which has the switch triggered.

Here's the code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
    }

    UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    [cell addSubview:theSwitch];
    cell.accessoryView = theSwitch;
    [theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];

    return cell;
}

- (void) switchChanged:(UISwitch *)sender {
    UITableViewCell *theParentCell = [[sender superview] superview]; // Throwing Warning here 
    NSIndexPath *indexPathOfSwitch = [mainTableView indexPathForCell:theParentCell];
    NSLog(@"the index path of the switch: %ld", (long)indexPathOfSwitch.row);
}

Here is the warning message:

Warning: "Incompatible pointer types initializing UITableViewCell * with an expression of type UIView *"

What the sender should be instead of superview?

5
  • Try only one superview call. But probably an easier way to do this is just set the Switch's tag to the index path row. Jul 26, 2014 at 14:04
  • I set the tag. And where should I use it? Jul 26, 2014 at 14:06
  • Did you try using the tag based approach instead? It's much easier and quicker. The UITableViewCell view hierarchy is a little strange. Jul 26, 2014 at 14:10
  • If you are sure it's the right view you can add an explicit cast to silence the warning. Jul 26, 2014 at 14:11
  • 1
    This approach (which is not just for buttons) is much better than tags and looking at superviews.
    – user467105
    Jul 26, 2014 at 15:15

2 Answers 2

4

If I understand correctly you are trying to get the switch parent cell index.

-(NSIndexPath *)indexPathWithSubview:(UIView *)subview {
    while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
        subview = subview.superview;
    }
    return [self.mytable indexPathForCell:(UITableViewCell *)subview];
}

- (void) switchChanged:(UISwitch *)sender {
    NSIndexPath *apath = [self indexPathWithSubview:(UISwitch *)sender];
}
0
1

I recently ran across this. Here is the swift equivalent code

func indexPathWithSubview(subview: UIView) -> NSIndexPath {
  var view = subview
  while view.isKindOfClass(UITableViewCell) {
    view = view.superview!
  }
  return tableView.indexPathForCell(view as! UITableViewCell)!
}

func switchChanged(sender: UISwitch) {
  let indexPath = indexPathWithSubview(sender)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.