【问题标题】:iOS: Could not cast value of type NextViewContrller to UINavigationControlleriOS:无法将 NextViewContrller 类型的值转换为 UINavigationController
【发布时间】:2017-12-25 10:10:02
【问题描述】:

我正在尝试实现 navegationController 以编程方式在视图控制器之间切换:

@IBAction func next(_ sender: Any) {
        self.performSegue(withIdentifier: "next", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "next"{
            let destNVC = segue.destination as! UINavigationController
            let next = destNVC.topViewController as! NextViewController
            next.title = "next!"
        }
    }

但我收到此错误:

Could not cast value of type 'myProject.NextViewController' (0x108de5338) to 'UINavigationController' (0x10aa2d4a8).

你们中的任何人都知道我为什么会收到这个错误吗?

非常感谢您的帮助。

【问题讨论】:

    标签: ios swift3 uinavigationcontroller xcode8


    【解决方案1】:

    我假设截图中最右边的 VC 是你的NextViewController

    让我们看看在这种情况下segue.destination 是什么。很容易找到segue.destination 所指的内容。查看你的故事板,找到你想要的转场,然后用箭头找到转场的结尾。无论箭头指向什么 VC,都是segue.destination。 (segue 的另一端是segue.source btw)

    现在我们知道了这一点,我们知道在这种情况下segue.destination 必须引用NextViewController。现在您应该意识到应该更正这一行:

    let destNVC = segue.destination as! UINavigationController
    

    好吧,尝试将NextViewController 转换为UINavigationController 肯定会导致错误,不是吗?

    事实上,你可以将segue.destination 转换为NextViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "next"{
            let next = segue.destination as! NextViewController
            next.title = "next!"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2021-09-29
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 2017-03-02
      • 2015-08-17
      • 2018-04-22
      相关资源
      最近更新 更多