【问题标题】:UINavigationController appDelegate UIViewController programmaticallyUINavigationController appDelegate UIViewController 以编程方式
【发布时间】:2018-03-02 22:45:45
【问题描述】:

我正在尝试以编程方式创建一个 UINavigationController 和两个 UIVewController,并能够使用导航控制器从第一个 VC 转换到第二个 VC 并返回。我尝试了不同的方法来让它工作。我在源代码中留下了一些注释掉的行,以提示我尝试过的事情。

使用当前方法我收到此警告(它不起作用):

警告:尝试在视图不在窗口层次结构中的 <0x7fd27240db60><0x7fd27240df00>

&gt;

    标签: ios swift uiviewcontroller uinavigationcontroller programmatically


    【解决方案1】:

    结果:

    代码:

    AppDelegate:

        window = UIWindow()
        let firstVC = FirstViewController()
        let navigationController = UINavigationController(rootViewController: firstVC)
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
    

    第一VC:

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

    第二个VC:

    view.backgroundColor = .yellow
    

    希望对您有所帮助!请让我知道它是否适合您。

    【讨论】:

    • 是的,它有效。非常感谢你。但是在 viewDidLoad() 中只实例化一次 SecondViewController 会更好吗?
    • 是的。您还可以将其设为惰性 var,以便我认为只有在用户点击它时才会实例化它。
    猜你喜欢
    • 2011-05-23
    • 1970-01-01
    • 2014-01-13
    • 2014-11-25
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多