简体   繁体   English

如何从主视图加载子视图?

[英]How to load subview from the main view?

I am very new to Obj-C and learning iphone development. 我对Obj-C和学习iphone开发非常陌生。 My question is how to add subview from app delegate. 我的问题是如何从应用程序委托添加子视图。 Lets say I added subview called "MainView" from "applicationDidFinishLaunching" method. 可以说我从“ applicationDidFinishLaunching”方法添加了一个名为“ MainView”的子视图。

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

MainViewController *aViewController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
self.mainViewController = aViewController;
[aViewController release];

[window addSubview:mainViewController.view];
// Override point for customization after application launch
[window makeKeyAndVisible];

} }

"MainView.xib" file has a button to show its child view. “ MainView.xib”文件具有一个按钮来显示其子视图。 When the button is clicked, it calls "showChildView" method. 单击该按钮时,它将调用“ showChildView”方法。

- (IBAction)showChildView:(id)sender {
    if (self.childViewController == nil) {
        ChildViewController *childController = [[ChildViewController alloc] initWithNibName:@"ChildView" bundle:nil];
        self.childViewController = childController;
        [childController release];
    }

    [self.view insertSubview:childViewController.view atIndex:0];
}

From this code, when app launches, it shows "MainView" with a button. 从此代码中,应用程序启动时,将显示带有按钮的“ MainView”。 But when I clicked the button, the button is still visible as well as the content from the "ChildView.xib" file too. 但是,当我单击该按钮时,该按钮以及“ ChildView.xib”文件中的内容仍然可见。

How can I hide the "MainView" when I pressed the button and show only the contents of the "ChildView"? 按下按钮并仅显示“ ChildView”的内容时如何隐藏“ MainView”?

Thanks for your help in advance. 感谢您的帮助。

well, you have to remove the original view first, before inserting the new subview, do it this way 好吧,您必须先删除原始视图,然后再插入新的子视图,这样做

- (IBAction)showChildView:(id)sender {
    if (self.childViewController == nil) {
        ChildViewController *childController = [[ChildViewController alloc] initWithNibName:@"ChildView" bundle:nil];
        self.childViewController             = childController;
        [childController release];
    }
    [self.mainViewControlle.view removeFromSuperView];
    [self.view insertSubview:childViewController.view atIndex:0];
}

Hope this helps. 希望这可以帮助。

您可能想要查看Utility Utility示例-该示例演示了如何在两个带有动画的视图之间切换以及从父视图添加/删除视图。

you might want to create a navigation controller in the main view and than push the childviewcontroller onto it when invoking showChildView. 您可能要在主视图中创建一个导航控制器,而不是在调用showChildView时将childviewcontroller推到该视图上。 You'll get the back navigation button for free that way 这样您将免费获得后退导航按钮

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

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