访问另一个视图控制器的功能时意外发现 nil

Posted

技术标签:

【中文标题】访问另一个视图控制器的功能时意外发现 nil【英文标题】:unexpectedly found nil when accessing another view controller's functions 【发布时间】:2017-09-03 10:49:14 【问题描述】:

我在一个名为“BaseViewController.swift”的文件中有一个函数。当我在 viewDidLoad(在同一个文件中)中调用它时,它可以完美运行。

func setFrontView(to view: UIView)   
    if view == singlePlayerContainerView   
        singlePlayerContainerView.isHidden = false  
        twoPlayerContainerView.isHidden = true  
     else if view == twoPlayerContainerView   
        singlePlayerContainerView.isHidden = true  
        twoPlayerContainerView.isHidden = false  
     else   
        /  
        singlePlayerContainerView.isHidden = false  
        twoPlayerContainerView.isHidden = true  
      
  

我尝试在另一个名为“PlacesView.swift”的文件中调用它,在 collectionView DidSelectItem 中:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)   

    let cell: PlacesCollectionViewCell = collectionView.cellForItem(at: indexPath) as! PlacesCollectionViewCell  

    let superView = BaseViewController()  
    switch cell.modeTitleLabel.text!   
    case "Single Player":  
        superView.setFrontView(to: superView.singlePlayerContainerView)  
        print("incomplete func")  
    case "Two Player":  
        superView.setFrontView(to: superView.twoPlayerContainerView)  
        print("incomplete func")  
    case "Lie Mode":  
        print("incomplete func")  
    case "Master's Mode":  
        print("incomplete func")  
    case "Settings":  
        print("incomplete func")  
    default:  
        print("incomplete func")  
      
    print("Cell was tapped! Title: \(cell.modeTitleLabel.text!)")  

  

当我点击单人游戏或双人游戏(或调用函数的位置)时,它给我一个错误,说致命错误:在展开可选值时意外发现 nil

谢谢

【问题讨论】:

let superView = BaseViewController() 不起作用,您需要获取超级视图,而不是创建超级视图。 那我怎么说呢? 【参考方案1】:

这段代码永远不会正常工作,因为:

    您的新 ViewController 没有加载,它只是被创建了

    您的新 ViewController 不是父 ViewController

查看这里以了解如何获取 SuperViewController https://***.com/a/24590678/5482826

【讨论】:

以上是关于访问另一个视图控制器的功能时意外发现 nil的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 在展开可选值时意外发现 nil - 从委托调用变量

致命错误:在展开可选值 UIPageViewController 时意外发现 nil

使用 View Controller 作为辅助视图的委托失败,在展开可选时意外发现 nil

prepareForSegue 出错“”在展开可选值时意外发现 nil“”

在隐式展开可选值时意外发现 nil (UICollectionView)

不断出现致命错误:在展开可选值时意外发现 nil