本文介绍了以编程方式快速切换另一个导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我忽略故事板并在 AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))//make the ViewController class to be the root

    return true
}

我有 leftBarButton 切换到另一个 UINavigationControllerUICollectionViewController(根据你的建议)

I have leftBarButton which switches to another UINavigationController or UICollectionViewController(according to your advice)

override func viewDidLoad() {
    super.viewDidLoad()

    let parentMenuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 34, height: 34))
    parentMenuButton.addTarget(self, action: #selector(self.menuButtonOnClicked), for: .touchUpInside)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: parentMenuButton)
}

@objc func menuButtonOnClicked(){
    print("menuButtonOnClicked button is pressed")
}

如何以编程方式实现此目的?(按菜单按钮切换另一个导航区域)

How can I achieve this programmatically?(switch another navigation area by pressing menu button)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.navigationController!.pushViewController(secondViewController, animated: true)

错误:

由于未捕获的异常NSInvalidArgumentException"而终止应用,原因:Storyboard () 不包含标识符为SecondViewController"的视图控制器

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Storyboard () doesn't contain a view controller with identifier 'SecondViewController''

我创建了 SecondViewController:

I create SecondViewController:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

有没有办法在不弄乱情节提要的情况下做到这一点?(仅以编程方式)

Is there a way to do it without messing with storyboard?(only programatically)

推荐答案

你需要在你的menuButtonOnClicked()

 @objc func menuButtonOnClicked(){
    print("menuButtonOnClicked button is pressed")
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
    self.navigationController.pushViewController(secondViewController, animated: true)
    }

这篇关于以编程方式快速切换另一个导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 12:59