【问题标题】:Get the view a UIButton is on获取 UIButton 所在的视图
【发布时间】:2016-03-25 09:04:14
【问题描述】:

我在自定义 UITableViewCell 上有一个 UIButton,我有一个“完成”方法。

如何通过 Button 获取 CustomTableViewCell?

-(IBAction)done:(id)sender {
    (CustmCell((UIButton)sender).viewTheButtonIsOn...).action
}

【问题讨论】:

    标签: iphone objective-c ios


    【解决方案1】:

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

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

    【讨论】:

    • 你这个混蛋!在循环中很好地使用强类型。 ++
    【解决方案2】:

    如果直接将其作为子视图添加到单元格中,则可以使用-superview 获取它的父视图。此外,您需要使用指针进行强制转换,因为对象从不按值获取,仅在 Objective-C 中指向。

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

    【讨论】:

    • 如果按钮被添加到单元格的contentView,您将需要两次调用superview
    • 没错。您可以一遍又一遍地在 superview 上调用 superview,直到到达它的父视图。
    【解决方案3】:

    另一种方法是创建具有 CustomCell 属性的 UIButton 的子类,以直接访问 CustomCell 对象。这在技术上比寻找超级视图的超级视图更好。

    【讨论】:

      【解决方案4】:

      您还必须考虑 contentView,或者现在或将来可能包含按钮的单元格的任何其他子视图。安全并遍历父层次结构。

      var parent = button.superview
      while let v = parent where !v.isKindOfClass(MyCustomCell)   {
          parent = v.superview
      }
      
      // parent is now your MyCustomeCell object
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-16
        • 1970-01-01
        • 1970-01-01
        • 2018-03-16
        • 2011-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多