首页 文章

'Unexpectedly found nil while unwrapping an Optional value'

提问于
浏览
-2

我想做一个只有在触摸按钮时才会出现的标签 . 当在MainViewController中调用函数 hidden() 时它's working well but when i'从ButtonAction类调用它(相同的函数)我得到一个经典错误:

在解开Optional值时意外发现nil

这是代码:

//  MainViewController.swift

import UIKit

class MainViewController: UIViewController {

    @IBOutlet weak var labelToShow: UILabel!
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        labelToShow.isHidden = true
    }

    func hidden() {
        labelToShow.isHidden = true
    }

    func inHidden() {
        labelToShow.isHidden = false
    }

}

AND:

//  ButtonAction.swift


import UIKit

class ButtonAction: UIButton {

    var touched:Bool = false
    var mainScreen = MainViewController()

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        sleep(1)
        mainScreen.hidden()
        touched = true
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        mainScreen.inHidden()
        touched = false
    }
}

2 回答

  • 1

    使用默认初始值设定项 MainViewController() 创建的 mainScreen 实例与Interface Builder中设计的实例不同 .

    您需要实际引用主视图控制器(通过 IBOutlet 或协议/委托等)

  • 0

    在该行代码中,您将创建MainViewController的新实例:

    var mainScreen = MainViewController()
    

    您必须获取 MainViewController() 实例的引用(由 storyboard 自动创建)

相关问题