以编程方式快速呈现视图控制器 [英] Presenting a view controller programmatically in swift
问题描述
我正在尝试将以下目标 C 代码转换为 swift,以便在单击按钮时从一个视图控制器导航到另一个视图控制器.任何帮助将不胜感激
Hi I am trying to convert the following objective C code into swift to navigate from one view controller to another view controller when a button is clicked. any help would be much appreciated
这是摘自苹果的编程指南
This is taken from apple's programming guide
- (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 嵌入了导航控制器
my code is indicated below, but not sure how to implement in the navigation controller, in the storyboard my mainSectionViewController is embedded with a Navigation Controller
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)
}
推荐答案
是否以模态呈现 navController?
Do you want to present navController modally?
如果是,这就是答案
self.presentViewController(navController, animated: true, completion: nil)
"self" 是将呈现 navController 的当前视图控制器
"self" is the current view controller that will present the 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)
}
}
但是,
如果你想在navigationController中的viewController之间导航,可以使用
If you want to navigate between viewController in the navigationController, you can use
self.navigationController.pushViewController(viewControllerToPush, animated: true)
这篇关于以编程方式快速呈现视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!