我想要做一个只有当按钮被触摸时才会出现的标签。 当函数隐藏()被称为MainViewController它的工作很好,但,当我从ButtonAction类(功能相同),我得到一个经典的错误称之为:'意外地发现零,同时解开一个可选值'
Unexpectedly found nil while unwrapping an Optional value
下面的代码:
// 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
}
}
你可以显示完整的代码如何创建ButtonAction类和ViewController? –
可能的重复[什么是“致命错误:意外地发现零,而解包可选值”是什么意思?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil- while-unwrapping-an-optional-valu) – rmaddy