用透明背景呈现模态视图控制器

9

我想以编程方式呈现一个UIViewController,它应该以透明的背景出现(或者不出现)。 我需要它适用于iOS 7.0及以上版本。我自己找到了很多问题(和答案),但它们无法帮助我。这是我的应用程序的视图层次结构。

我正在使用侧边菜单控制器(RESideMenu)。

我有一个根视图(基于RESideMenu) -> 在 UINavigationController 中显示中心控制器(以及左侧视图控制器)。

在要求中,我想呈现一个视图控制器

从推送的视图控制器(在导航层次结构中)

从呈现的视图控制器(在导航层次结构中)

此外,我需要呈现它并执行一些操作,然后将其删除。

我非常确定这在许多情况下都应该有效,无论是带有侧边菜单还是没有,甚至是导航控制器。

我发布了一个单独的问题(当然也包括其答案),因为我认为这将对可能也被这个问题困扰的社区开发人员有所帮助。

1个回答

15
假设我们现在在FirstViewController中。
//Obj-C
- (void) presentSecondVC {
    SecondViewController *vc = [[SecondViewController alloc] init];
    [self addChildViewController:vc];
    [self didMoveToParentViewController:vc];
}

//Swift
func presentSecondVC() {
    let vc = SecondViewController.init()
    self.addChildViewController(vc)
    self.didMove(toParentViewController: vc)
}

有些人可能需要像这样编写上述方法:
//Obj-C
- (void) presentSecondVC {
    SecondViewController *vc = [[SecondViewController alloc] init];
    vc.view.frame = CGRectMake(0,0,width,height); //Your own CGRect
    [self.view addSubview:vc.view]; //If you don't want to show inside a specific view
    [self addChildViewController:vc];
    [self didMoveToParentViewController:vc];
    //for someone, may need to do this.
    //[self.navigationController addChildViewController:vc];
    //[self.navigationController didMoveToParentViewController:vc];   
}

//Swift
func presentSecondVC() {
    let vc = SecondViewController.init()
    vc.view.frame = CGRect.init(x: 0, y: 0, width: width, height: height) //Your own CGRect
    self.view.addSubview(vc.view) //If you don't want to show inside a specific view.
    self.addChildViewController(vc)
    self.didMove(toParentViewController: vc)
    //for someone, may need to do this.
    //self.navigationController?.addChildViewController(vc)
    //self.navigationController?.didMove(toParentViewController: vc)
}

现在在SecondViewController中,当您想要返回时。
//Obj-C
- (void) goBack {
    [self removeFromParentViewController];
}

//Swift
func goBack() {
    self.removeFromParentViewController()
}

请注意适应各种情况 :)

是的,在我的情况下,这不会显示动画。不过,我正在 vc 中显示一个自定义弹出窗口,使用此代码效果很好!


23
亲爱的给我点踩的人,请考虑一下在评论中说明你点踩的原因,这样有助于我学习和提高自己。我将我的回答保留在这里(就像我的问题一样),以帮助你(和其他开发者们)。但是,如果它看起来不好或者对你没有用,那么请随意写下你的想法(如果可能的话,请附上你的解决方案),并在你点踩的同时表达出来。我一定会感激不尽,谢谢! :) - Hemang
方法 goBack 不完整,应该调用 removeFromSuperViewUIViewController Class Reference 适合您。 - DawnSong
你需要在两种情况下都添加 [self.view addSubview:vc.view]; 这一行代码... 只有 addChildViewController 不会起作用... - Mihir Mehta
主要的downvotes原因是你的回答说如何添加子视图控制器,而不是如何呈现视图控制器,它们之间有很大的区别。https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/PresentingaViewController.html#//apple_ref/doc/uid/TP40007457-CH14-SW1 对于那些感兴趣的人,请阅读苹果文档。 - Iraniya Naynesh
@IraniyaNaynesh,感谢你的光临,这个问题我几年前已经回答过了。请随意编辑问题细节或我的答案,以获得完美的画面。祝Doovery一切顺利! :) P.S. 我不再在意那些点踩了。 - Hemang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接