如何在另一个类的标签中更新计数器的值?



我在StopWatch类中有一个向上计数的对象,在ViewController类中有一个显示其值的标签。我使用@Published@ObservedObject属性包装器来共享和观察counter的值。

如何在标签中自动更新计数器的值?

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()
}
}

@ObservedObject只在SwiftUI视图中工作。在这种情况下,可以直接通过Publisher观察published属性,如

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

最新更新