我正在重建没有情节提要的应用程序,而我遇到最大麻烦的部分是以编程方式浏览视图到视图。很少有东西不用情节提要写出来,因此很难找到答案。
我的问题很简单。我有我ViewController和我SecondViewController,我想从前者推向后者。
ViewController
SecondViewController
在AppDelegate:
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:
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返回零。我试着做:
self.navigationController
var navController = UINavigationController()当ViewController创建类时(但在ViewDidLoad外部,在类声明的正下方),并使用navControllervar 完成了推送,但这没有用。
var navController = UINavigationController()
navController
我在想,也许解决方案是在App Delegate中创建整个应用程序都将使用的导航控制器,我想这是一个全局变量吗?
我希望这篇文章可以为许多其他Swift初学者并希望从其应用中删除情节提要的用户提供服务。
感谢您的光临和帮助。
在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()