问题
I want to present a UIViewController
programmatically which should show up (or not, rather) with transparent background. I want it for iOS 7.0 and above. I've find myself many questions (and answers) but they weren't able to help me. Here's the view hierarchy of my app.
I'm using a side menu controller (RESideMenu).
I have a rootView (base from RESideMenu) -> Showing a Center controller (along with a left view controller) in UINavigationController
.
In requirements, I'd like to present a view controller
From a pushed view controller (in navigational hierarchy)
From a presented view controller (in navigational hierarchy)
In addition, I need to present it and perform some action, and then remove it.
I'm pretty sure that this should work in many cases, with (or without) side menu, or even navigation controller.
I'm posting a separate question (and of course its answer too) into this queue, because I think it would prove helpful to the community devs who might also have been frustrated by the lack of an acceptable solution to this problem.
回答1:
Suppose, we're in
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)
}
Some of you may need to write above method like this,
//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)
}
Now in
SecondViewController
when you want to go back
//Obj-C
- (void) goBack {
[self removeFromParentViewController];
}
//Swift
func goBack() {
self.removeFromParentViewController()
}
Do play well (with each scenario) :)
And yes, this will not show an animation, in my case, I'm showing a custom popup inside vc
though it looks nice with this code!
来源:https://stackoverflow.com/questions/27598846/present-a-modal-view-controller-with-transparent-background