VC推送时出现线程1错误?

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

我的应用程序目前有3个VC。 rootVC模拟地通过UIButton呈现第二个VC - 它工作正常 - 但是我在第二个VC中的UILabel点击后出现第三个VC时遇到问题。

这是处理点击的SecondVC中的代码:

var goToStats : UILabel {
        var label = UILabel()
        label.frame = CGRect(x:0, y:0, width: 300, height: 60)
        label.center = CGPoint(x: view.center.x, y: view.center.y + 250)
        label.text = "Statistical Breakdown"
        label.font = UIFont(name: "Arial", size: 30)
        label.textAlignment = .center
        label.backgroundColor = UIColor(
                displayP3Red: 1/255,
                green: 102.0/255,
                blue: 102.0/255,
                alpha: 1)
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
        return label
        }

    view.addSubview(goToStats)
}

@objc func handleTap() {
    print("Tapped!")

    let thirdVC = ThirdVC()
    self.navigationController!.present(thirdVC, animated: true, completion: nil)
}

运行时,我收到以下错误:

error

有什么解释吗?我想也许没有与第二个VC关联的导航控制器(因为它返回nil),但VC本身位于导航堆栈上,所以我不认为这是这种情况。这是我的第三个VC的问题吗?这是当前的代码:

import Foundation
import UIKit

class thirdVC : ViewController {


override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.green
}

}

谢谢你的时间!

swift segue
1个回答
1
投票

你的rootViewController可能是一个navigationController,但当你present这样的事情,

let secondVC = SecondVC()
self.navigationController!.present(secondVC, animated: true, completion: nil)

这并不意味着SecondVC将有一个navigationController。要获得navigationControllerSecondVC,你需要将这个ViewController嵌入navigationController中,如下所示,

let secondVC = SecondVC()
let secondNavC = UINavigationController(rootViewController: secondVC)
self.navigationController!.present(secondNavC, animated: true, completion: nil)

现在,如果您将从ThirdVC呈现以下SecondVC,那么它将起作用

let thirdVC = ThirdVC()
self.navigationController!.present(thirdVC, animated: true, completion: nil)

如果你没有在ViewController中嵌入第二个UINavigationController,那么你会得到那次崩溃,因为你是强行解开(!navigationController,这在第二个ViewController中没有。

© www.soinside.com 2019 - 2024. All rights reserved.