UINavigationController appDelegate UIViewController以编程方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UINavigationController appDelegate UIViewController以编程方式相关的知识,希望对你有一定的参考价值。
我正在尝试以编程方式创建UINavigationController和两个UIVewControllers,并能够使用导航控制器从第一个VC转换到第二个VC并返回。我已经尝试了不同的方法让它工作。我在源代码中留下了一些注释,以提示我尝试过的一些事情。
使用当前方法,我收到此警告(它不起作用):
警告:尝试在<x.VC1:0x7fd27240db60>上显示<x.VC2:0x7fd27240df00>,其视图不在窗口层次结构中!
在AppDelegate.swift中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let navcon = UINavigationController()
//navcon.viewControllers = [VC1(), VC2()] // tried this without success
navcon.viewControllers = [VC1()]
window = UIWindow()
window?.makeKeyAndVisible()
//window?.rootViewController = VC1() // one variation that I tried
window?.rootViewController = navcon.viewControllers[0]
return true
}
在VC1.swift中:
var navcon: UINavigationController!
let vc2 = VC2()
//---------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
navcon = self.navigationController
//navcon?.viewControllers.append(vc2)
let x = navcon?.viewControllers
let n = x?.count
}
//---------------------------------------------
func triggeredFunction() {
self.present(vc2, animated: true, completion: nil)
//navcon.pushViewController(vc2, animated: true)
}
码:
AppDelegate中:
window = UIWindow()
let firstVC = FirstViewController()
let navigationController = UINavigationController(rootViewController: firstVC)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
FirstVC:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
button.backgroundColor = .red
view.addSubview(button)
button.addTarget(self, action: #selector(showSecondVC), for: .touchUpInside)
}
@objc func showSecondVC() {
let secondVC = SecondViewController()
navigationController?.pushViewController(secondVC, animated: true)
}
SecondVC:
view.backgroundColor = .yellow
希望能帮助到你!如果它适合您,请告诉我。
以上是关于UINavigationController appDelegate UIViewController以编程方式的主要内容,如果未能解决你的问题,请参考以下文章
iOS:如何在现有 UINavigationController 中打开另一个 UINavigationController?
带有主 UINavigationController 和详细 UINavigationController 的 UISplitViewcontroller
带有 UINavigationController 的 UITabBarController,在 hidesBottomBarWhenPushed 上隐藏 UINavigationController
在 UINavigationController 内的 UITabBarcontroller 中添加 UINavigationController?
UINavigationController 与 AppDelegate 中的 UISegmentedControl 切换 UINavigationController 的 rootviewcontr
从一个 UINavigationController 到另一个 UINavigationController (Swift iOS 9, xcode 7)