-2

I'd like to do a label which is present only when button is touched. When function hidden() is called in MainViewController It's working well but when i'm calling it from ButtonAction class (same function) I get an classic error:

Unexpectedly found nil while unwrapping an Optional value

Here's the code:

//  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
    }
}
4

2 回答 2

1

使用默认初始化器创建的mainScreen实例与 MainViewController()在 Interface Builder 中设计的实例不同。

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

于 2016-12-16T10:52:18.890 回答
0

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

var mainScreen = MainViewController()

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

于 2016-12-16T11:00:54.787 回答