[英]UINavigationController appDelegate UIViewController programmatically
I'm trying to create a UINavigationController and two UIVewControllers programmatically and be able to transition from the first VC to the second VC and back using the navigation controller. 我正在尝试以编程方式创建一个UINavigationController和两个UIVewControllers,并且能够使用导航控制器从第一个VC过渡到第二个VC,然后再返回。 I've tried different methods for getting this to work.
我尝试了不同的方法来使其工作。 I've left some lines in the source code commented out to give hints of things that I've tried.
我在源代码中留下了一些注释,以提示我尝试过的事情。
With the current method I'm getting this warning (it doesn't work): 使用当前方法,我会收到此警告(它不起作用):
Warning: Attempt to present <x.VC2: 0x7fd27240df00> on <x.VC1: 0x7fd27240db60> whose view is not in the window hierarchy!
警告:尝试在其视图不在窗口层次结构中的<x.VC1:0x7fd27240db60>上显示<x.VC2:0x7fd27240df00>!
In AppDelegate.swift: 在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
}
In VC1.swift: 在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)
}
Code: 码:
AppDelegate: AppDelegate:
window = UIWindow()
let firstVC = FirstViewController()
let navigationController = UINavigationController(rootViewController: firstVC)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
FirstVC: 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: SecondVC:
view.backgroundColor = .yellow
Hope it helps! 希望能帮助到你! Please let me know if it works for you or not.
请让我知道它是否适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.