Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get indexPath of UITableViewCell by clicking subview of the cell - Getting incompatible pointer type warning

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?

like image 505
Kenan Karakecili Avatar asked Jul 26 '14 13:07

Kenan Karakecili


2 Answers

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];
}
like image 162
modus Avatar answered Sep 30 '22 18:09

modus


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)
}
like image 39
Kenan Karakecili Avatar answered Sep 30 '22 18:09

Kenan Karakecili