ios - UIView.addSubview() 意外发现nil

标签 ios swift

这是我的问题:

我在类中有一个函数。该类有一个名为 embeddedView 的 socket 。当该函数在类内调用时,它可以访问该 socket ,但当在其他地方调用时,它会失败。

func embedView(_ newView: UIViewController){
        self.navigationItem.title = selectedView
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: Style.sectionHeaderTitleColor]
        newView.view.frame = self.embeddedView.bounds
        self.embeddedView.addSubview((newView.view)!) //This is the line that fails from AppDelegate
        addChildViewController(newView)
        newView.didMove(toParentViewController: self)
 }

当从类内部调用时,该函数没有问题,但当从 AppDelegate 调用时,它会失败,并出现错误 fatal error :展开可选值时意外发现 nil,因为嵌入 View 是声明了 !

非常感谢任何帮助!

最佳答案

您对 AppDelegate 中的变量 self.embeddedView 有强引用吗?通常,AppDelegate 类中没有可用的 UIView,因为它不与任何 UIView 关联。 AppDelegate 是初始化所有其他 UIView 的起点。出现此错误的原因是您的 View self.embeddedView 实际上在 AppDelegate 处为 nil,但是当您在 UIViewController 中使用相同的 View 时 类,您可以使用该对象并且它可以工作。

关于ios - UIView.addSubview() 意外发现nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43587740/

相关文章:

swift - API 返回无效指针的问题

ios - iPhone 应用程序 PayPal 集成

ios - UINavigationItem 动画

html - iOS APNS 创建消息

ios - 最好在约束更改之前或之后调用 .layoutIfNeeded()

ios - 侧边菜单 BarPosition 错误 iOS 9

swift - 带量程的开关盒

ios - 从初始化程序返回而不初始化所有存储的属性

ios - 当 VoiceOver 打开时,应用程序是否可以检测单指(左右)滑动?

ios - 如何在 iOS 应用程序中使用标准经典蓝牙配置文件?