以下是在iOS开发中,当前ViewController添加一个子ViewController,并通过点击按钮控制子ViewController的显示和隐藏的完整代码。

在当前ViewController的.h文件中声明一个属性用于存储子ViewController:

@property (strong, nonatomic) UIViewController *childViewController;

在当前ViewController的.m文件中添加以下代码:

// 在当前ViewController的某个方法中创建并添加子ViewController
self.childViewController = [self.storyboard instantiateViewControllerWithIdentifier:'ChildViewController']; // 通过Storyboard创建子ViewController
[self addChildViewController:self.childViewController]; // 添加子ViewController到当前ViewController

// 将子ViewController的view添加到当前ViewController的view中
self.childViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:self.childViewController.view];
[self.childViewController didMoveToParentViewController:self];

// 创建一个按钮用于控制子ViewController的显示和隐藏
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20, 20, 100, 40);
[button setTitle:'Toggle' forState:UIControlStateNormal];
[button addTarget:self action:@selector(toggleChildViewController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

// 控制子ViewController的显示和隐藏方法
- (void)toggleChildViewController {
    if (self.childViewController.view.superview) {
        [self.childViewController willMoveToParentViewController:nil];
        [self.childViewController.view removeFromSuperview];
        [self.childViewController removeFromParentViewController];
    } else {
        [self addChildViewController:self.childViewController];
        self.childViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        [self.view addSubview:self.childViewController.view];
        [self.childViewController didMoveToParentViewController:self];
    }
}

通过以上代码,就可以在当前ViewController中添加一个子ViewController,并通过点击按钮控制子ViewController的显示和隐藏。

iOS开发:在当前ViewController添加子ViewController并控制显示隐藏

原文地址: https://www.cveoy.top/t/topic/o9oV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录