这是我的问题:
我在类中有一个函数。该类有一个名为 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/