美文网首页
在UITableViewCell的继承类里获取自己的indexP

在UITableViewCell的继承类里获取自己的indexP

作者: 出门请右拐 | 来源:发表于2016-09-24 15:17 被阅读637次

继承了UITableViewCell,有些时候,我们需要在某个方法里面获取到indexPath,可以通过父子视图关系来找到对应的table view,在通过table view的对象方法,得到当前的indexPath:

// uses the indexPathForCell to return the indexPath for itself
- (NSIndexPath *)getIndexPath {
    return [[self getTableView] indexPathForCell:self];
}

// retrieve the table view from self
- (UITableView *)getTableView {
    // get the superview of this class, note the camel-case V to differentiate
    // from the class' superview property.
    UIView *superView = self.superview;

    /*
     check to see that *superView != nil* (if it is then we've walked up the
     entire chain of views without finding a UITableView object) and whether
     the superView is a UITableView.
     */
    while (superView && ![superView isKindOfClass:[UITableView class]]) {
        superView = superView.superview;
    }

    // if superView != nil, then it means we found the UITableView that contains
    // the cell.
    if (superView) {
        // cast the object and return
        return (UITableView *)superView;
    }

    // we did not find any UITableView
    return nil;
}

相关文章

网友评论

      本文标题:在UITableViewCell的继承类里获取自己的indexP

      本文链接:https://www.haomeiwen.com/subject/snuxyttx.html