2

I've created a custom UItableviewcell with an embedded segmented control, when the segmented control is clicked I have a method that requires the row index path. Using iOS7 the following is working well, I get the index path and can then update the other values within the custom cell.

    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[[sender superview] superview] superview]];

Unfortunately when I test this using iOS6 the indexPath is being set to NULL, is there now a difference in the way this works for iOS6 & iOS7?

Duncan Hill
  • 547
  • 2
  • 5
  • 16

4 Answers4

1

Having do a little research I wasn't doing this is the best way, instead of using the superview I now search the view hierarchy.

UIView *view = sender;
while (![view isKindOfClass:[UITableViewCell class]]) {
    view = [view superview];
}

This now works for both iOS6 & 7, one other issue that I've encountered is that the default height for a segmented control is different for iOS7 and affects the row heigh.

Duncan Hill
  • 547
  • 2
  • 5
  • 16
  • I suspected that the view hierarchy had changed. Using logic like "the view that is 3 superviews up is the TableViewCell" is not very stable. – paulrehkugler Oct 09 '13 at 20:57
  • To search the view hierarchy is in general not very stable. Also your code could cause an endless loop if the sender is not within a UITableViewCell. – Felix Oct 09 '13 at 21:00
0

You could create a subclass of UISegmentedControl and add an indexPath property, then just set the indexPath in cellForRowAtIndexPath:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SegmentCell *returnCell = [tableView dequeueReusableCellWithIdentifier:@"SegmentCell" forIndexPath:indexPath];
    returnCell.segmentedControl.indexPath = indexPath;

    return returnCell;
}

Much cleaner and if the view hierarchy changes, your solution doesn't break.

JonahGabriel
  • 3,066
  • 2
  • 18
  • 28
0

This is the best way I think:

CGPoint subviewPosition = [sender convertPoint:CGPointZero toView:self.myTable];

NSIndexPath* indexPath = [self.myTable indexPathForRowAtPoint:subviewPosition];

Regardless of whether it is iOS6 or 7, it will return the correct index path

Gautam Jain
  • 2,913
  • 30
  • 25
-1

This is because in iOS7 UITableViewWrapperView is the superview of UITableViewCell unlike iOS6

You should use

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {      
//iOS7

NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[[sender superview] superview] superview]];

} else {

//iOS6

NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];

}

Thanks to null (UITableViewCell indexPath crash in iOS7)

Community
  • 1
  • 1
Ashish
  • 169
  • 2
  • 10