【问题标题】:How to update Text with property observers in ContentView when input variable is changed更改输入变量时如何在 ContentView 中使用属性观察器更新文本
【发布时间】:2020-07-15 02:21:38
【问题描述】:

使用 XCode 11.4、Swift 5.0

每当我创建的变量(存储在应用程序的用户默认值中)发生更改时,我希望更新 ContentView 中的文本变量 (correctionLabel)。下面的代码显示了我尝试在输入变量更改时使用didSet 更新 ContentView 中的文本:

//ContentView.swift
//this is a single page application


import SwiftUI

let defaults = UserDefaults.standard

var correctionLabel = Text("O")
var corrections = defaults.integer(forKey: "CorrectionCount") {
    didSet {
        correctionLabel = Text("\(corrections)")
        print("old value is \(oldValue) and new value is \(corrections)")
        print(correctionLabel)
    }
}

struct ContentView: View {
    var body: some View {

        correctionLabel

    }
}

//code for incrementing the corrections variable not shown here

该应用程序的其他所有内容都经过测试并且可以正常工作,使用print() 测试进行验证,以确保在更改 iPhone 方向时corrections 变量确实在增加。 但是,屏幕上的计数器从 0 开始但从不增加,并且控制台显示 print(correctionLabel) 的此错误:

Text(storage: SwiftUI.Text.Storage.anyTextStorage(SwiftUI.(unknown context at $1cf871518).LocalizedTextStorage), modifiers: [])

我觉得问题一定是小问题,我在这里遗漏了一些东西,因为所需的最终产品是一个简单的屏幕计数器,它从 0 开始并以 1 递增。非常感谢任何见解!

【问题讨论】:

    标签: properties textview swift5 xcode11 observers


    【解决方案1】:

    找到解决方案:

    我使用了 SwiftUI 新的 @EnvironmentObject 的实现, 在这里查看一个不错的教程:https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

    如果你在一个类中使用一个函数,比如我要更新你的变量(在这种情况下它是校正变量),请确保你引用的是类函数的同一个实例,而不是调用类函数!

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 2014-11-02
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 2015-08-20
      • 2021-01-31
      • 2019-01-14
      相关资源
      最近更新 更多