UINavigationController appDelegate UIViewController以编程方式

问题描述 投票:0回答:1

我正在尝试以编程方式创建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)
}
ios swift uiviewcontroller uinavigationcontroller programmatically
1个回答
0
投票

结果:enter image description here

码:

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

希望能帮助到你!如果它适合您,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.