Execute a method when a variable value changes in Swift

后端 未结 5 1619
时光说笑
时光说笑 2020-12-25 10:47

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

I have a singleton class containing a shared variable called labelChange. Values of this va

5条回答
  •  没有蜡笔的小新
    2020-12-25 11:31

    In Swift 4 you can use Key-Value Observation.

    label.observe(\.text, changeHandler: { (label, change) in
        // text has changed
    })
    

    This is basically it, but there is a little catch. "observe" returns an NSKeyValueObservation object that you need to hold! - when it is deallocated, you’ll receive no more notifications. To avoid that we can assign it to a property which will be retained.

    var observer:NSKeyValueObservation?
    // then assign the return value of "observe" to it
    observer = label.observe(\.text, changeHandler: { (label, change) in
        // text has changed,
    })
    

    You can also observe if the the value has changed or has been set for the first time

    observer = label.observe(\.text, changeHandler: { (label, change) in
        // just check for the old value in "change" is not Nil
        if let oldValue = change.oldValue {
            print("\(label.text) has changed from \(oldValue) to \(label.text)")
        } else {
            print("\(label.text) is now set")
        }
    
    })
    

    For More Information please consult Apples documentation here

提交回复
热议问题