如何获得uitableviewcell的超级视图

时间:2012-05-14 10:01:39

标签: objective-c uitableview

我想获得uitableviewcell的父视图,它是自定义的。我尝试使用自我超级视图来获取父表视图,但它没有用。

 - (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);
...
}

Nslog输出的值总是0。

@jrturton已经给出了自我超级视图无法引用其父视图的原因。但接下来的问题是我想在单元格初始化时获取indexPath。

3 个答案:

答案 0 :(得分: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"]);
}

答案 1 :(得分:0)

您必须遍历视图层次结构。 This 会帮助你

答案 2 :(得分:-3)

尝试使用[cell.contentView addSubview:imgTemp];希望它会对您有所帮助。

相关问题