Swift:无法以编程方式查看控制器

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

我正在尝试使用此代码以编程方式推送到不同的视图控制器:

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! MenuController
self.navigationController?.pushViewController(loginVC, animated: true)

这是我的设置:我有swift文件名为:MenuController,其中包含此代码我将标识符名称设置为:LoginViewController我将两个ViewControllers的类设置为MenuController。但每当我按下按钮触发事件时,它都不会做任何事情。

这是我要求的其余代码:

import UIKit

class MenuController: UIViewController {

    var thingy = 0

    @IBAction func ThingyBttn(_ sender: UIButton) {
        if(thingy == 1) {
            print("ok")
        }else{
            print("good")

            let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! MenuController
            self.navigationController?.pushViewController(loginVC, animated: true)
        }
    }

    @IBOutlet var myButton: UIButton!

    @IBAction func Button(_ sender: UIButton) {
        if let ButtonImage = myButton.image(for: .normal),
            let Image = UIImage(named: "ButtonAppuyer.png"),
            UIImagePNGRepresentation(ButtonImage) == UIImagePNGRepresentation(Image) {
            thingy = 1

            print("1")                
        } else {
            thingy = 2

            print("2")
        }   
    }

}

我知道代码的其他一切工作正常,因为它正在打印消息。

swift viewcontroller
2个回答
1
投票

您需要在navigationController中插入vc,因为这样做

self.navigationController?

nil,还是以编程方式进行

编辑:

替换它

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! MenuController
self.navigationController?.pushViewController(loginVC, animated: true)

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! MenuController
let nav = UINavigationController(rootViewController:self) 
(UIApplication.shared.delegate as! AppDelegate).window!.rootViewController = nav 
nav.pushViewController(loginVC, animated: true)

0
投票

我认为你的视图控制器不在Navigation Stack,这就是为什么它没有推向下一个视图控制器

let nextVC = self.storyboard?.instantiateViewController(withIdentifier: “nextvc”) as! nextvc
let navigation = UINavigationController(rootViewController:self) 
UIAppliaction.window!.rootViewController = navigation  
navigation.pushViewController(nextVC, animated: true)
© www.soinside.com 2019 - 2024. All rights reserved.