【发布时间】:2020-02-19 03:08:27
【问题描述】:
我的模型的主要类是 Concentration,带有一个名为 flipCount 的属性
class Concentration {
@objc var flipCount = 0
在我的 ViewController 中,我有一个 @IBOutlet 到一个名为 FlipCountLabel 的 UILabel
class ViewController: UIViewController {
lazy var game = Concentration(numberOfPairsOfCards: self.cardButtons.count / 2)
@IBOutlet weak var flipCountLabel: UILabel!
...
我想在flipCount 更改时更新flipCountLabel 中的文本。我试图通过在我的 ViewController 的 viewDidLoad 方法中调用 UIViewController 的观察方法来做到这一点。有几种观察方法。我不知道哪个是正确的,也找不到如何填写变量的示例。
我尝试过使用 self.observe 之类的
self.observe(KeyPath<Concentration,Int>(game, "flipCount"), changeHandler: {
self.flipCountLabel.text = "Flip Count: \(flipCount)"
})
每次更新 game.flipCount 时,我都会尝试更新 ViewControllers flipCountLabel.text。 我认为这是 kvo?
【问题讨论】:
-
@Don 我无法在 Concentration 类中访问 FlipCountLabel。 IBOutlet 在 ViewController 中
-
哦,对不起。没有仔细阅读。
标签: ios swift model-view-controller key-value-observing