简体   繁体   English

从另一个视图控制器向视图控制器添加子视图

[英]add subview to a view controller from another view controller

I have two view controller classes. 我有两个视图控制器类。 On the first, I have an image view and on second view controller there is a text view. 在第一个视图中,我有一个图像视图,在第二个视图控制器中,有一个文本视图。 The second view controller has a done-button, on clicking done-button I want to add a label on the first view controller's image and pass text view's text on that label. 第二个视图控制器具有完成按钮,单击“完成”按钮后,我想在第一个视图控制器的图像上添加标签,并在该标签上传递文本视图的文本。 Is there any way to do it? 有什么办法吗? Please suggest me. 请给我建议。

Use delegates. 使用委托。 Create a protocol on the Second view controller and make the First view controller its delegate. 在第二个视图控制器上创建一个协议,并将第一个视图控制器作为其委托。 Use delegate methods to send the textview's text as message to the delegate (or in general, send any kind of data between classes). 使用委托方法将textview的文本作为消息发送给委托(或通常在类之间发送任何类型的数据)。

Keep a reference to the second view controller in the first view controller. 在第一视图控制器中保留对第二视图控制器的引用。

Call a public function in the second view controller from the first view controller. 从第一视图控制器在第二视图控制器中调用公共函数。

View Controller A: 视图控制器A:

@interface ViewControllerA : UIViewController
{
@public
    NString *text;
}

View Controller B: 查看控制器B:

@interface ViewControllerB : UIViewController
{
@public
    ViewControllerA *refToA;
}

Code to launch view controller B from A: 从A启动视图控制器B的代码:

ViewControllerB *vc = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
vc->refToA = self;
[self presentModalViewController:vc animated:YES];

in View Controller B set the value: 在View Controller B中设置值:

refToA->text = @"text to pass";
[refToA.view addSubview:button];

View did appear in A: 视图确实出现在A:

- (void)viewDidAppear:(BOOL)animated
{
   if (text != nil)
   {
     NSLog(@"%@", text);
     // create your button here
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM