我正在重建一个没有 Storyboard的应用程序,其中我遇到最大麻烦的部分是以编程方式导航 View 到 View 。那里写的东西很少不使用 Storyboard ,因此很难找到答案。
我的问题很简单。我有我的 ViewController
和我的 SecondViewController
,我想从前者推送到后者。
在 AppDelegate
中:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
然后在 ViewController.swift
中:
class ViewController: UIViewController, AVAudioPlayerDelegate, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
startFinishButton.setTitle("Begin", forState: .Normal)
startFinishButton.addTarget(self, action: "moveToSecondViewController", forControlEvents: .TouchUpInside)
view.addSubview <*> startFinishButton
}
func moveToSecondViewController(sender: UIButton) {
let vc = SecondViewController()
println(self.navigationController) // returns nil
self.navigationController?.pushViewController(vc, animated: true)
}
}
打印 self.navigationController
返回 nil。我试过这样做:
var navController = UINavigationController()
当创建 ViewController
类时(但在 ViewDidLoad 之外,在类声明的正下方)并使用 完成推送navController
var 但这没有用。
我在想,也许解决方案是在 App Delegate 中创建一个整个应用程序都会使用的导航 Controller ,我猜是作为一个全局变量?
我希望这篇文章可以为许多其他刚接触 Swift 并希望从他们的应用程序中删除 Storyboard 的人提供帮助。
感谢您的关注和帮助。
最佳答案
在 Swift 3 中
将此代码放在 AppDelegate 类的 didFinishLaunchingWithOptions 方法中。
window = UIWindow(frame: UIScreen.main.bounds)
let mainController = MainViewController() as UIViewController
let navigationController = UINavigationController(rootViewController: mainController)
navigationController.navigationBar.isTranslucent = false
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
关于ios - Swift——在 App Delegate 中实例化一个没有 Storyboard的导航 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30956476/