获取UIButton所在的视图

phi*_*ipp 6 iphone objective-c ios

我在自定义UITableViewCell上有一个UIButton,我有一个方法"完成".

如何通过Button获取CustomTableViewCell?

-(IBAction)done:(id)sender {
    (CustmCell((UIButton)sender).viewTheButtonIsOn...).action
}
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 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];
}
Run Code Online (Sandbox Code Playgroud)

  • 你这个卑鄙!在循环中使用强大的打字功能.++ (3认同)

Cod*_*aFi 5

如果将其作为子视图直接添加到单元格,则可以使用-superview它来获取其父视图.此外,您需要使用指针进行强制转换,因为对象永远不会被值占用,只能在Objective-C中指向.

-(IBAction)done:(id)sender {
    [(CustmCell*)[(UIButton*)sender superview]someAction];
}
Run Code Online (Sandbox Code Playgroud)

  • 如果按钮被添加到单元格的`contentView`,你将需要两次调用`superview`。 (2认同)