I have a counting-upward object in StopWatch
class and a label showing its value in ViewController
class. I used @Published
and @ObservedObject
property wrappers for sharing and observing counter
's value.
How could I automatically update counter's value in a label?
ViewController.swift
import UIKit
import SwiftUI
class ViewController: UIViewController {
@ObservedObject var stopWatch = StopWatch()
@IBOutlet var label: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
label.text = "\(self.stopWatch.counter)"
}
@IBAction func start(_ sender: UIButton) { self.stopWatch.start() }
@IBAction func stop(_ sender: UIButton) { self.stopWatch.stop() }
}
StopWatch.swift
class StopWatch: ObservableObject {
@Published var counter: Int = 0
var timer = Timer()
func start() {
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0,
repeats: true) { _ in
self.counter = 1
}
}
func stop() {
self.timer.invalidate()
}
}
CodePudding user response:
The @ObservedObject
works only inside SwiftUI view. In this case it is possible to observe published property directly via Publisher, like
import Combine
class ViewController: UIViewController {
let stopWatch = StopWatch()
@IBOutlet var label: UILabel!
private var cancellable: AnyCancellable!
override func viewDidLoad() {
super.viewDidLoad()
cancellable = stopWatch.$counter.sink { [weak self] newValue in
self?.label.text = "\(newValue)"
}
}
// ... other code