【问题标题】:Get UIView property value in UIViewController在 UIViewController 中获取 UIView 属性值
【发布时间】:2014-07-24 10:09:52
【问题描述】:

我有一个 CustomView(UIView 的子类),其中包含一些奇怪的 UIButton,当单击 ViewController 上的按钮时会显示这些按钮。我如何在 ViewController 的 CustomView 中获取按钮的标签值。

自定义视图.m - 我将设置按钮标签 = 005

ViewController.m - 我怎样才能在这里得到 005?

我浏览了下面的 SO 帖子,但不知道如何实现它。 LINK1LINK2

【问题讨论】:

  • 你有没有在 ViewController 中引用过 CustomView?
  • @Greg No.我在 ViewController.m 中使用 [[CustomView alloc] initWithFrame:]

标签: objective-c ios7 uiview uiviewcontroller delegates


【解决方案1】:

如果您在 ViewController 中引用了您的 CustomView,您可以执行以下操作:

for (UIView *v in self.customView.subviews) {
    if ([v isKindOfClass:[UIButton class]]) {
        int tag = v.tag;
    }
}

但是,如果您没有对自定义视图的任何引用,请尝试以下操作:

for (UIView *v in self.view.subviews) {
    if ([v isKindOfClass:[CustomView class]]) {
        CustomView customView = (CustomView*)v;
        for (UIView *v1 in customView.subviews) {
            if ([v1 isKindOfClass:[UIButton class]]) {
                int tag = v.tag;
                break; // You have the tag exit loop
            }
        }
        break; // you have custom view exit loop
    }
}

【讨论】:

    【解决方案2】:

    您不需要使用委托或任何东西。你只需要在 ViewController 中引用 CustomView 然后使用类似的东西:

    for (UIView *view in [_myCustomView subviews]) {
        if ([view isKindOfClass:([UIButton class])]) { 
            //Test the tag
            if (view.tag == 5) {
                //found it! do something with it.
                break;
            }
         }
    }
    

    要在视图控制器中添加引用,请将其添加到 .m 文件的 @interface 部分

    @property (strong, nonatomic) CustomView* myCustomView;
    

    然后,当您创建自定义视图时,将其分配给 myCustomView,如下所示:

    _myCustomView = [[CustomView alloc] init...];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2012-08-02
      • 1970-01-01
      相关资源
      最近更新 更多