ios - 以编程方式快速切换另一个导航

标签 ios swift uinavigationcontroller

我忽略 Storyboard并在 AppDelegate.swift 中创建 UINavigationController

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(根据您的建议)

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")
}

enter image description here

如何以编程方式实现这一点?(通过按菜单按钮切换另一个导航区域)

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

错误:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“Storyboard () 不包含标识符为‘SecondViewController’的 View Controller ”

我创建了 SecondViewController:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

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

}

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

最佳答案

您需要在 menuButtonOnClicked() 中调用 push 方法

 @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)
    }

关于ios - 以编程方式快速切换另一个导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447780/

相关文章:

ios - 从 View Controller 返回后 UINavigationBar titleTextAttributes 未更新

iphone - didSelectRowAtIndexPath : nested push animations

iphone - xcconfig 文件中的预处理器宏

ios - Swift,如何在遵循 MVC 的同时声明需要实例成员的方法

json - Swift:如果我复制 JSON 数据的 AnyObject,数据会被复制还是通过引用传递?

ios - Swift 1/2 TextField 标签显示所有名称

ios - 在 animateAlongsideTransition block 内的 UIImage 上进行交叉溶解

iphone - 从不同线程访问 UIView 的简单快捷方式

iphone - 如何在不提交到应用程序商店的情况下向客户展示 iPhone 应用程序(临时分发)

处理程序 block 的 Swift 数组