我该如何以编程方式以模态形式呈现视图控制器?

21

编辑: 在解决这个问题时,我发现从您的UITabBarController开始会更容易,然后通过您的AppDelegate.mdidFinishLaunchingWithOptions:方法执行登录验证。

问题: 这段代码位于我的AppDelegate.m中的application didFinishLaunchingWithOptions:方法中。

if([result isEqualToString: @"log"])
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *ivc = [storyboard instantiateViewControllerWithIdentifier:@"TabBarControl"];
    [(UINavigationController*)self.window.rootViewController pushViewController:ivc animated:NO];
    NSLog(@"It's hitting log");
}

只需对HTTP响应进行处理以确定用户是否已登录,并将其传递给我的TabBarController即可。问题在于它使用了push而不是modal转换来显示页面。由于presentModalViewController方法在iOS7中已被弃用或删除,我该如何编写程序以强制执行模态呈现?

编辑:


3
你只需要查看此方法的参考文档,它会告诉你应该使用什么替代方法,不改变原意,使语言更加通俗易懂。 - rmaddy
1
在此图像中,您似乎正在使用segue向后(除了unwind segue)返回到先前的控制器,这是不应该的。这将导致新的控制器被实例化,而不是返回到您开始的那个控制器。 - rdelmar
4个回答

30

Swift

以下是在Swift中不引用导航控制器的实现方式:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

根据需要更改故事板名称、视图控制器和id。

另请参阅如何以编程方式解除视图控制器


如果您想从任意的UI上下文中执行此操作,可以使用UIWindow.visibleVC?.present。 - Andy Weinstein

2
在Swift 4.2中,您可以像这样完成它。对于那些希望在更新版本的Swift中得到答案的人。
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ExampleViewController")
self.present(controller, animated: true, completion: nil)

0

在Swift 3/4中

     let storyB = UIStoryboard(name: "Main", bundle: nil) 
     let secondViewController = storyB.instantiateViewController(withIdentifier: "SecondViewControllerID") as! SecondViewController
     self.present(secondViewController, animated: true, completion: nil)

0
 let storyB = UIStoryboard(name: "Main", bundle: nil) 
 let secondViewController = 
 storyB.instantiateViewController(withIdentifier: 
 "SecondViewControllerID") as! SecondViewController
 self.present(secondViewController, animated: true, completion: nil)

在 secondViewController 中使用以下代码返回。
 self.dismiss(animated: true, completion: nil)

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