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

时间:2017-09-03 10:49:15

标签: ios swift xcode

我在名为'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

THX

1 个答案:

答案 0 :(得分:0)

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

  1. 您的新ViewController未加载,仅创建了

  2. 您的新ViewController不是父ViewController

  3. 检查一下,了解如何获得SuperViewController https://stackoverflow.com/a/24590678/5482826