简体   繁体   中英

Bind a swift variable to another one

I wanted to be able to bind a variable to a UILabel. I tried to create some sort of timer and I wanted to make sure that every time a variable counter gets modified, then also the text in the label will be updated automatically without writing it explicitly.

I thought of using something like this:

var _counter: Double = 0.0 
    var counter: Double{
        get{
            return _counter;
        }

        set{
            timeLabel.text = String(newValue);
            _counter = newValue;
        }

}

But I'm not sure if this is the best way (I also didn't managed to make it work this way).

What would you suggest to do?

Well to make your code work, you can try this:

var _counter: Double = 0.0 {
       didSet{
       timeLabel.text = String("\(_counter)")
       //old values can be retrieved by calling print("\(oldValue)")
       }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM