获取一个 UIButton 所在的视图

6

我在自定义的UITableViewCell上有一个UIButton,我有一个名为“done”的方法。

如何通过按钮获取CustomTableViewCell?

-(IBAction)done:(id)sender {
    (CustmCell((UIButton)sender).viewTheButtonIsOn...).action
}
4个回答

12

CodaFi的回答可能已经足够了,但它确实假设按钮直接添加到表格单元格中。稍微复杂一些但更安全的代码可能是:

-(IBAction)done:(id)sender {
    UIView *parent = [sender superview];
    while (parent && ![parent isKindOfClass:[CustomCell class]]) {
        parent = parent.superview;
    }

    CustomCell *cell = (CustomCell *)parent;
    [cell someAction];
}

3
你这个懦夫!循环中使用了较强类型的优秀技巧。++ - CodaFi

5

如果将其直接添加到单元格作为子视图,您可以使用 -superview 来获取其父视图。此外,由于 Objective-C 中的对象永远不会按值传递,只能指向它们,因此需要使用指针进行类型转换。

-(IBAction)done:(id)sender {
    [(CustmCell*)[(UIButton*)sender superview]someAction];
}

2
如果按钮被添加到单元格的contentView中,您将需要两个对superview的调用。 - rmaddy
没错。您可以一遍又一遍地在父视图上调用superview,直到达到其父视图。 - CodaFi

2
另一种方法是创建一个UIButton的子类,具有CustomCell属性,以直接访问CustomCell对象。从技术上讲,这比查找父视图的父视图更好。

1

您还需要考虑contentView以及单元格中任何其他子视图,无论是现在还是将来包含按钮的。为了安全起见,请遍历父级层次结构。

var parent = button.superview
while let v = parent where !v.isKindOfClass(MyCustomCell)   {
    parent = v.superview
}

// parent is now your MyCustomeCell object

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接