简体   繁体   中英

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).

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:

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

View Controller B:

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

Code to launch view controller B from A:

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

in View Controller B set the value:

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

View did appear in A:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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