SwiftUI 设置将触发视图刷新的外部变量

use*_*232 1 global-variables swift swiftui combine

iOS 13、Swift 5、Xcode 11.3.1

学习 SwiftUI。我把它放在一起,它有效,但它是正确的。

External.swift 中

class BlobModel: ObservableObject {
  @Published var score: String = "" 
}

var globalBlob = BlobModel()
Run Code Online (Sandbox Code Playgroud)

ContentView.swift 中

struct ContentView: View {

@ObservedObject var globalBlob:BlobModel

var body: some View {
  Text("\(globalBlob.score)")
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
      ContentView(globalBlob: globalBlob)
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在External.swift 中写入 globalBlob 时,它会更新显示。

globalBlob.score = backToString
Run Code Online (Sandbox Code Playgroud)

但是 globalBlob 是一个全局变量,这肯定是糟糕的编码实践。有没有更好的方法我应该这样做?

lor*_*sum 8

您可以从更改分数的类访问 Singleton 实例吗? https://developer.apple.com/documentation/swift/cocoa_design_patterns/managing_a_shared_resource_using_a_singleton

struct ContentView: View {

    @ObservedObject var globalBlob: BlobModel = BlobModel.sharedInstance

    var body: some View {
        VStack{
            Button(action: {self.globalBlob.score = Int.random(in: 0...100).description}, label: {Text("update-score")})
            Text("\(globalBlob.score)")
        }
    }

}

class BlobModel: ObservableObject {
    static let sharedInstance = BlobModel()
    @Published var score: String = ""
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)