简体   繁体   中英

how do i add a UIView controller to a UIView

i have a custom class of type UIViewController . i want to add it to a UIView so that it can be used to output to the screen.

the UIView is called engineView my custom UIViewController is called Engine. there is a custom method in the controller called addImage.

the code is as follows:

Engine *engine = [[Engine alloc] init];
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
engine.view.frame = frame;

UIImage *image = [UIImage imageNamed:@"photo2.jpg"];
[engine addImage:image];

[engineView addSubview: engine.view];

this does not display the image.

however if i add the view controller through storyboard, it seems to work (if i add the image at the viewdidlayoutsubviews method. but i would like to call functions to it programically from the parent UIViewCcontroller .

can anyone tell me how i do this?

在此处输入图片说明

You can set storyBoard identifier in interface builder and ca use it like suggested above.

  MyViewController *instance = [self.storyBoard instantiateViewControllerWithIdentifier:@"yourIdentifier"];

As far as adding a ViewController to UIView you can achieve that by using addChildViewController method too.

try like this..

Engine *engine = (Engine *)[self.storyboard instantiateViewControllerWithIdentifier:@"EngineViewControllerStoryBoardID"];

to set the story board id
在此处输入图片说明

to pass an image to Engine:

-->create a UIImage property in Engine.h

like @Property UIImage * engineImage;

--> assign that image to UIIMageView in Engine.m

-(void)viewWillAppear:(BOOL)animated
{ 


    engineImageView.image = engineImage; // engineImageView is an example UIImageView replace it with your UIImageView

}

--> now send the image like engine.engineImage =[UIImage imageNamed:@"photo2.jpg "];

 try this..

     Engine *eng=[self.storyboardinstantiateViewControllerWithIdentifier:@"YourStoryboradId"];

*you can set storyboard id by going in Identity Inspector.

设置StoryboardId After that You can add image on your View Controller by following code

        UIImageView *image=[UIImageView alloc]initWithFrame:CGRectMake(x, y, your width, your Height);
        img setImage:[UIImage imageNamed:@"imageName"];
        [eng addSubview:image];

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