1

I want to get the parent view of uitableviewcell, which was created custom. And I try to use self superview to get the parent tableview ,but it is unuseful.

 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization cod
        UITableView *tableView = (UITableView *)[self superview];
        NSIndexPath *indexPath = [tableView indexPathForCell:self];
        NSLog(@"%d %d", indexPath.section, indexPath.row);
...
}

The value that Nslog output is totally 0.

@jrturton has given the reason why self superview can not refer to its parent view. but next question is that I want to get the indexPath when the cell initial.

8
  • duplicate stackoverflow.com/a/1110522/986169
    – giorashc
    May 14, 2012 at 10:04
  • try using self.nextResponder.
    – rishi
    May 14, 2012 at 10:06
  • 3
    It is null at that point because your cell hasn't been added to a table yet. It has no superview.
    – jrturton
    May 14, 2012 at 10:41
  • 1
    What are you actually trying to do? If you wanted to do that, you'd do it in cellForRowAtIndexPath, but this would change when the cell was reused.
    – jrturton
    May 14, 2012 at 10:47
  • 1
    You could create a property to hold the cell's indexPath or if you need it during init, create a custom init method and pass it in
    – wibosco
    May 14, 2012 at 11:24

3 Answers 3

1
- (void)didTapButton:(id)sender {
    // Cast Sender to UIButton
    UIButton *button = (UIButton *)sender;

    // Find Point in Superview
    CGPoint pointInSuperview = [button.superview convertPoint:button.center toView:self.tableView];

    // Infer Index Path
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInSuperview];

    // Fetch Item
    NSDictionary *item = [self.dataSource objectAtIndex:indexPath.row];

    // Log to Console
    NSLog(@"%@", item[@"title"]);
}
0

you have to iterate through the view hierachry. This will help you

1
  • thanks, I try to use the way that you provide, but it also can't work. and I post my code on above May 14, 2012 at 10:40
-3

Try to use [cell.contentView addSubview:imgTemp]; Hope it will help you.

1
  • I do not want to add a subview on the contentview, but thank you May 14, 2012 at 10:41

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.