如何访问另一个 class 中的变量并更改其值

how to acces a variable in another class and change its value

我是 Xcode 和 Swift 的新手,所以我不太了解它们是如何工作的,但我正在尝试制作一个弹出视图。我希望在单击按钮时弹出一个小视图。该视图是一个视图容器(我不知道这是否是最好的方法,如果不是,请告诉我更好的方法),它开始时是隐藏的,然后当我单击一个按钮时它就会变得可见。此视图容器还有一个按钮,如果单击该按钮,它将使视图再次隐藏。

代码如下:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBOutlet weak var popUpView: UIView!

    @IBAction func startButton(sender: UIButton) {
        popUpView.hidden = false
    }

}

import UIKit

class PopUpViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       // Dispose of any resources that can be recreated.
    }

    override func  prepareForSegue(segue:UIStoryboardSegue,
                                   sender:AnyObject?) 
    {
       // Get the new view controller using segue.destinationViewController.
       // Pass the selected object to the new view controller.
    }

    @IBAction func backButton(sender: UIButton) {
        ViewController().popUpView.hidden = true
    }


}

当我 运行 应用程序启动正常,因为开始按钮在那里,当我点击它时弹出窗口出现,但是当我点击后退按钮时,它给我一个错误,说在控制台

未知 class Interface Builder 文件中的 MKMapView。 致命错误:在展开可选值时意外发现 nil

第 31 行 ViewControler().popUpView.hidden = true

它说线程 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0)

谁能帮忙。谢谢

从 didPrepareForSeque 方法访问 popUpView 变量(当您转到另一个视图时会自动调用此方法)。问题是,如果您尝试将值设置为 soon(意思是,该按钮未在视图中绘制),您将得到 nil 错误。这是一个小解决方法。您使用临时变量 (tmpValue) 来存储按钮的状态(是否隐藏),因此当 viewDidLoad 时,您的方法将读取此值并将按钮设置为您想要的隐藏状态。

在ViewControllerclass声明临时变量(必须是可选的):

var tmpValu:Bool?

然后在您的 PopUpViewController class 中从 backButton 操作中删除此行:

ViewController().popUpView.hidden = true

相反,您将使用 prepareForSegue 方法,如下所示:

 override func prepareForSegue(segue: UIStoryboardSegue, sender:  AnyObject?) {
   let destinationViewController = segue.destinationViewController as! ViewController
   destinationViewController.tmpValu = true
 }

现在,返回 ViewController class 在 vi​​ewDidLoad 中添加此代码:

override func viewDidLoad() {
    super.viewDidLoad()
    if let value = tmpValu {
        popUpView.hidden = value
    }
}