在Swift中更改变量值时执行方法 [英] Execute a method when a variable value changes in Swift

查看:181
本文介绍了在Swift中更改变量值时执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当变量值更改时,我需要执行一个函数.

I need to execute a function when a variable value changes.

我有一个单例类,其中包含一个名为labelChange的共享变量.此变量的值取自另一个名为Model的类.我有两个VC类,其中一个有一个按钮和一个标签,第二个只有一个按钮.

I have a singleton class containing a shared variable called labelChange. Values of this variable are taken from another class called Model. I have two VC classes, one of them has a button and a label and the second only a button.

当按下第一个VC类中的按钮时,我正在使用此func更新标签:

When the button in the first VC class is pressed I am updating the label with this func:

func updateLabel(){
    self.label.text = SharingManager.sharedInstance.labelChange
}

但是每当labelChange的值更改时,我都想调用相同的方法.因此,在按钮单击中,我将仅更新labelChange值,并且当发生这种情况时,我想使用labelChange的新值来更新标签.同样,在第二个VC中,我可以更新labelChange值,但是当该值更改时,我无法更新标签.

But I want to call the same method whenever the value of the labelChange is changed. So in button click I will only update the labelChange value and when this thing happen I want to update the label with the new value of the labelChange. Also in the second VC I am able to update the labelChange value but I am not able to update the label when this value is changed.

也许属性是解决方案,但是任何人都可以向我展示如何做到这一点.

Maybe properties are the solution but can anyone show me how to do so.

第二次

单班:

class SharingManager {
    func updateLabel() {
        println(labelChange)
        ViewController().label.text = SharingManager.sharedInstance.labelChange     
    }
    var labelChange: String = Model().callElements() {
        willSet {
            updateLabel()
        }
    }
    static let sharedInstance = SharingManager()
}

第一个VC:

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!
    @IBAction func Button(sender: UIButton) {    
       SViewController().updateMessageAndDismiss()
    }
}

第二个VC:

func updateMessageAndDismiss() {
        SharingManager.sharedInstance.labelChange = modelFromS.callElements()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
@IBAction func b2(sender: UIButton) { 
        updateMessageAndDismiss()
}

我做了一些改进,但是我需要引用单例中第一个VC类的标签.因此,我将在单例中更新该VC标签.

I made some improvements but I need to reference a label from the first VC class in singleton. Therefore I will update that label of VC in singleton.

当我打印labelChange的值时,该值正在更新,一切都很好.但是,当我尝试从单例更新标签上的该值时,会收到错误消息:

When I print the value of labelChange the value is being updated and everything is fine. But when I try to update that value on label from singleton I receive an error:

在展开可选值时意外发现nil

unexpectedly found nil while unwrapping an Optional value

错误指向单例类的第4行.

and the error is pointing in 4th line of singleton class.

推荐答案

您只需为变量labelChange使用属性观察器,然后在didSet(或willSet)内部调用要调用的函数如果要在设置之前调用它):

You can simply use a property observer for the variable, labelChange, and call the function that you want to call inside didSet (or willSet if you want to call it before it has been set):

class SharingManager {
    var labelChange: String = Model().callElements() {
        didSet {
            updateLabel()
        }
    }
    static let sharedInstance = SharingManager()
}

我不确定为什么在尝试时不起作用,但是如果由于尝试调用的函数(updateLabel)在另一个类中而遇到麻烦,则可以在SharingManager类,用于存储在调用didSet时要调用的函数,在这种情况下,应将其设置为updateLabel.

I'm not sure why this didn't work when you tried it, but if you are having trouble because the function you are trying to call (updateLabel) is in a different class, you could add a variable in the SharingManager class to store the function to call when didSet has been called, which you would set to updateLabel in this case.


因此,如果您要从ViewController编辑标签,则希望在ViewController类中具有该updateLabel()函数来更新标签,但是将该函数存储在singleton类中,以便它可以知道要调用哪个函数:

So if you want to edit a label from the ViewController, you would want to have that updateLabel() function in the ViewController class to update the label, but store that function in the singleton class so it can know which function to call:

class SharingManager {
    static let sharedInstance = SharingManager()
    var updateLabel: (() -> Void)?
    var labelChange: String = Model().callElements() {
        didSet {
            updateLabel?()
        }
    }
}

,然后在具有您要调用的函数的任何类中进行设置,例如(假设updateLabel是您要调用的函数):

and then set it in whichever class that you have the function that you want to be called, like (assuming updateLabel is the function that you want to call):

SharingManager.sharedInstance.updateLabel = updateLabel

当然,您需要确保负责该功能的视图控制器仍然存在,以便单例类可以调​​用该功能.

Of course, you will want to make sure that the view controller that is responsible for that function still exists, so the singleton class can call the function.

如果您需要根据可见的视图控制器调用不同的功能,则可能需要考虑

If you need to call different functions depending on which view controller is visible, you might want to consider Key-Value Observing to get notifications whenever the value for certain variables change.

此外,您永远也不想像这样初始化视图控制器,然后立即设置视图控制器的IBOutlet,因为在实际加载其视图之前,IBOutlets不会被初始化.您需要以某种方式使用现有的视图控制器对象.

Also, you never want to initialize a view controller like that and then immediately set the IBOutlets of the view controller, since IBOutlets don't get initialized until the its view actually get loaded. You need to use an existing view controller object in some way.

希望这会有所帮助.

这篇关于在Swift中更改变量值时执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆