UINavigationController appDelegate UIViewController以编程方式

业无高卑志当坚,男儿有求安得闲?这篇文章主要讲述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 triedwindow?.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) }

答案结果:
UINavigationController appDelegate UIViewController以编程方式

文章图片

码:
AppDelegate中:
window = UIWindow() let firstVC = FirstViewController() let navigationController = UINavigationController(rootViewController: firstVC) window?.rootViewController = navigationController window?.makeKeyAndVisible()

FirstVC:
override func viewDidLoad() { super.viewDidLoad()view.backgroundColor = .greenlet 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以编程方式】希望能帮助到你!如果它适合您,请告诉我。

    推荐阅读