【问题标题】:Add, remove subview and communicate between subview and main uiviewcontroller添加、删除子视图并在子视图和主 uiviewcontroller 之间进行通信
【发布时间】:2013-07-27 01:40:08
【问题描述】:

我在情节提要中创建了两个 uiviewcontroller。当按下按钮时,我将第二个 UIview 作为子视图添加到第一个视图。

现在,我的子视图有一个完成和取消按钮,一旦被触摸,子视图必须从主视图中删除,并且需要将一些数据发送回主视图。使用代表是解决这个问题的唯一方法吗?请说明是否还有其他更简单或更好的选择。

谢谢你:)

【问题讨论】:

    标签: objective-c uiview uiviewcontroller uibarbuttonitem addsubview


    【解决方案1】:

    听起来问题只是关于第一个视图控制器视图的子视图。在这种情况下,第一个视图控制器可以直接检查所有这些。即假设您希望在视图之间“传递”的数据是子视图中包含的 UITextField 的文本。

    你有一个子视图的出口,可能是在 IB 中绘制的?

    // MyViewController.m
    @property(weak, nonatomic) IBOutlet UIView *subview;  // self.view is it's parent
    

    创建一个连接到您想要从中获取数据的任何子视图的插座:

    @property(weak, nonatomic) IBOutlet UITextField *textField;   // probably, subview is it's parent
    

    隐藏和显示“对话框”:

    self.subview.alpha = 0.0;  // to hide (alpha is better than 'hidden' because it's animatable
    self.subview.alpha = 1.0;  // to show
    

    按下按钮时:

    - (IBAction)pressedDoneButton:(id)sender {
    
         self.subview.alpha = 0.0;
    
         // or, prettier:
         [UIView animateWithDuration:0.3 animations:^{ self.subview.alpha = 0.0; }];
    
         // the text field still exists, it's just invisible because it's parent is invisible
        NSLog(@"user pressed done and the text that she entered is %@", self.textField.text);
    }
    

    关键是数据没有在视图之间传递。视图控制器具有指向视图的指针。有些像按钮会为视图控制器生成事件以做出反应。其他人携带视图控制器可以看到的数据。

    【讨论】:

    • 太棒了!!谢谢!!但是如果我使用 alpha 而不是 hidden.. 触摸时不会触发子视图的按钮(除了主视图按钮操作)? @danh
    • 没有。当它们的父 alpha 为零时,任何子视图都将忽略触摸。
    • 另外,如果 subview 是其中所有对象的父级,这是否意味着为 subviewW 创建不同的 .h 和 .m? @danh
    • 不。包含子视图是视图工作的一部分。您将使用一个新文件对视图进行子类化,以赋予它特殊的新行为。但听起来默认行为就是您所需要的。
    • ok..所以我可以在 mainview .h 中声明文本字段吗?我怎么能说 subview 是他们的父母? @danh
    猜你喜欢
    • 1970-01-01
    • 2011-10-26
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多