【问题标题】:Switch another navigation programmatically swift以编程方式快速切换另一个导航
【发布时间】:2018-11-23 13:39:41
【问题描述】:

我忽略情节提要并在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")
}

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

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

错误:

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

我创建 SecondViewController:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

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

}

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

【问题讨论】:

    标签: ios swift uinavigationcontroller


    【解决方案1】:

    你需要在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)
        }
    

    【讨论】:

    • 你的代码没有按照 xcode 的建议工作,我把你的代码改成问题
    • 你需要设置你的viewController的标识符..检查更新的答案只是进入你的故事板给类和故事板IDSecondViewController
    • 有没有办法在不弄乱情节提要的情况下做到这一点?(更新问题)
    • 不,你不能:(你需要在界面生成器中设置它
    猜你喜欢
    • 1970-01-01
    • 2014-03-07
    • 2015-05-12
    • 2020-05-27
    • 1970-01-01
    • 2023-03-06
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多