我一直在遵循firebase教程来创建自己的聊天应用程序,我试图从包含表视图的uiviewcontroller访问chatviewcontroller。Viewcontroller嵌入在导航控制器中。选择单元格后,如何打开chatviewcontroller?
这是我的代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    //retrieve the destination view controller
    let navVc = segue.destination as! UINavigationController

    let channelVc = navVc.viewControllers.chatViewController as! ViewController

    // set the senderDisplayName in Viewcontroller to the email provided in the email field by the user

    channelVc.senderDisplayName = userEmailTextField?.text
}

Here is the error msg

最佳答案

假设ChatViewController是导航控制器的根视图控制器,则应将代码更改为:

let channelVc = navVc.viewControllers.first as! ChatViewController

navVC.viewControllers是由UIViewController管理的UINavigationController的数组,因此除非您实现了自定义的特性,否则该数组将没有名为chatViewController的属性。
编辑:要将所有内容放在一起,并演示如何安全地展开这些选项,您的prepareForSegue应该如下所示:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    if let navVc = segue.destination as? UINavigationController, let channelVc = navVc.viewControllers.first as? ChatViewController {
        //Now you have a reference to your ChatVC, and you can set the DisplayName
        channelVc.senderDisplayName = userEmailTextField?.text
    }
}

关于ios - 如何转换uinavigationview Controller 的第一个 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43664639/

10-11 14:48