首页 文章

使用导航控制器在故事板中呈现视图控制器 - Swift

提问于
浏览
38

我目前正在我的新故事板中显示一个viewController:

var storyboard : UIStoryboard = UIStoryboard(name: AccountStoryboard, bundle: nil)
var vc : WelcomeViewController = storyboard.instantiateViewControllerWithIdentifier("WelcomeID") as WelcomeViewController
vc.teststring = "hello"        
self.presentViewController(vc, animated: true, completion: nil)

但是,这使得viewcontroller没有嵌入式导航控制器 . 我尝试将“WelcomeID”更改为故事板中的导航控制器 - 但是没有成功 .

我在Objective -C中使用了这个,但是不知道如何转换为swift:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"SetupStoryboard" bundle:nil];
UINavigationController *navigationController1 = [storyboard instantiateInitialViewController];
navigationController1.modalPresentationStyle = UIModalPresentationFormSheet;
navigationController1.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

WelcomeViewController *vc = (WelcomeViewController *)navigationController1.viewControllers[0];
vc.teststring = @"Hello";

[self presentViewController:navigationController1 animated:YES completion:nil];

你怎么能在swift中做到这一点?

4 回答

  • 89

    你肯定是在正确的轨道上 . 不幸的是,当您通过其故事板ID引用视图控制器时,它将忽略它嵌入任何内容的事实 . 对于segue,当你转向嵌入的东西时,目标视图控制器将是嵌入式控制器,而不是你通常感兴趣的控制器 . 无论如何,你应该能够以类似的方式修复问题 . Objective-C,所以这只是语法移植的练习 .

    Edit: Define storyboard name with string now

    let storyboard : UIStoryboard = UIStoryboard(name: "AccountStoryboard", bundle: nil)
    let vc : WelcomeViewController = storyboard.instantiateViewControllerWithIdentifier("WelcomeID") as WelcomeViewController
    vc.teststring = "hello"        
    
    let navigationController = UINavigationController(rootViewController: vc)
    
    self.presentViewController(navigationController, animated: true, completion: nil)
    

    或者,您可以为嵌入视图控制器提供ID并将其实例化 .

  • 9
    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("WelcomeID") as SecondViewController
    
            self.navigationController?.pushViewController(secondViewController, animated: true)
    

    类名是:SecondCiewController

    Identifier Name

  • 0

    @Chris给出的答案在较旧版本的swift中效果很好 .

    Update Swift 3 & Swift 4

    let storyboard : UIStoryboard = UIStoryboard(name: "AccountStoryboard", bundle: nil)
       let vc : WelcomeViewController = storyboard.instantiateViewController(withIdentifier: "WelcomeID") as! WelcomeViewController
       vc.teststring = "hello"
    
       let navigationController = UINavigationController(rootViewController: vc)
    
       self.present(navigationController, animated: true, completion: nil)
    

    谢谢!!!

  • 17
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "SalesVC") as! SalesVC
    
    navigationController?.pushViewController(vc, animated: true)
    

相关问题