【问题标题】:unexpectedly found nil when accessing another view controller's functions访问另一个视图控制器的功能时意外发现 nil
【发布时间】: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() 不起作用,您需要获取超级视图,而不是创建超级视图。
  • 那我怎么说呢?

标签: ios swift xcode


【解决方案1】:

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

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

  2. 您的新 ViewController 不是父 ViewController

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

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多