以Swift编程方式在应用中呈现视图控制器

15

嗨,我正在尝试将以下 Objective-C 代码转换为 Swift,在按钮点击时从一个视图控制器导航到另一个视图控制器。如有帮助,将不胜感激

这是来自苹果编程指南的内容。

  - (void)add:(id)sender {
 // Create the root view controller for the navigation controller
 // The new view controller configures a Cancel and Done button for the
 // navigation bar.
   RecipeAddViewController *addController = [[RecipeAddViewController alloc]
                   init];

 // Configure the RecipeAddViewController. In this case, it reports any
 // changes to a custom delegate object.
   addController.delegate = self;

 // Create the navigation controller and present it.
  UINavigationController *navigationController = [[UINavigationController alloc]
                         initWithRootViewController:addController];
  [self presentViewController:navigationController animated:YES completion: nil];
  }

我编写的代码如下所示,但不确定如何在导航控制器中实现,在故事板中,我的mainSectionViewController已经嵌入了一个导航控制器。

    func sectionBtnClicked (sender: UIButton!) {


        let sectionController = self.storyboard?.instantiateViewControllerWithIdentifier("mainSectionsVC") as mainSectionViewController


        let navController = UINavigationcontroler. ///not sure what actually comes here, any help would be appreciated


        self.presentViewController(navController, animated: true, completion: nil)


}
2个回答

24

你想以模态方式呈现navController吗?

如果是,这就是答案。

self.presentViewController(navController, animated: true, completion: nil)

"self"是当前的视图控制器,将呈现navController。

就像这样放置:

class ViewController: UIViewController {       

    override func viewDidLoad() {
        super.viewDidLoad()

        var theButton = UIButton()

        // Add the event to button
        theButton.addTarget(self, action: "buttonTouchInside:", forControlEvents: .TouchUpInside)

        self.view.addSubview(theButton)
    }

    func buttonTouchInside(sender:UIButton!)
    {
        // When the button is touched, we're going to present the view controller

        // 1. Wrap your view controller within the navigation controller

        let navController = UINavigationController(rootViewController: yourViewController)

        // 2. Present the navigation controller

        self.presentViewController(navController, animated: true, completion: nil)
    }

}

但是,

如果你想在导航控制器中在视图控制器之间进行导航,可以使用

self.navigationController.pushViewController(viewControllerToPush, animated: true)

15

我做了一个简单的解决方案。在这里..

func actioncall () {
    let loginPageView =  self.storyboard?.instantiateViewControllerWithIdentifier("LoginPageID") as! ViewController
    self.presentViewController(loginPageView, animated: true, completion: nil)
}

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