【问题标题】:Switching to a new ViewController in a different ViewController?在不同的 ViewController 中切换到新的 ViewController?
【发布时间】:2011-03-24 21:17:02
【问题描述】:
我知道您可以使用中间类从一个 ViewController 切换到另一个,如 this example 所示。
我想知道的是,有没有办法直接从另一个视图控制器切换到另一个视图控制器?比如,在当前视图控制器中加载视图,然后立即释放你所在的那个?
谢谢。
【问题讨论】:
标签:
iphone
objective-c
ios
uiviewcontroller
【解决方案1】:
我认为您要求的是如何保留 1 个视图控制器。
您可以做的是,当您添加新的视图控制器时,将其添加到您的父视图控制器并删除当前的视图控制器。
【解决方案2】:
使用 UINavigationController 是一种方式:[navigationController pushViewController:animated:]。另一种“官方”方式是将下一个视图显示为模态视图:[someVC presentModalViewController:],但自 iOS 6 起已弃用。
iOS 6 的方式是:-(void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion。
【解决方案3】:
var currentVC:UIViewController!
let firstVC = yourViewcontroller1()
let secondVC = yourViewcontroller2()
func setupChildViewControllers(){
self.addChildViewController(firstVC)
self.addChildViewController(secondVC)
self.view.addSubview(firstVC.view)
self.currentVC = firstVC
}
func replaceController(oldVC:UIViewController,newVC:UIViewController){
self.addChildViewController(newVC)
self.transitionFromViewController(oldVC, toViewController: newVC, duration: 0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: nil) { (finished) -> Void in
if finished {
newVC.didMoveToParentViewController(self)
oldVC.willMoveToParentViewController(nil)
oldVC.removeFromParentViewController()
self.currentVC = newVC
}else{
self.currentVC = oldVC
}
}
}