我有以下课程
class GettingData: ObservableObject {
var doneGettingData = false
{
didSet {
if doneGettingData {
print("The instance property doneGettingData is now true.")
} else {
print("The instance property doneGettingData is now false.")
}
}
}
}
然后在mapView结构中更新变量doneGettingData,然后在主视图(contentView)中使用它。 在加载地图时,此变量从false / true更改,我可以从我在该类中使用的打印内容中检测到它,因此我知道它正在更改。 我想用它来触发ContentView中的微调器,这里有以下代码:
import SwiftUI
import Combine
struct ContentView: View {
var done = GettingData().doneGettingData
var body: some View {
VStack {
MapView().edgesIgnoringSafeArea(.top)
Spacer()
Spinner(isAnimating: done, style: .large, color: .red)
}
}
struct Spinner: UIViewRepresentable {
let isAnimating: Bool
let style: UIActivityIndicatorView.Style
let color: UIColor
func makeUIView(context: UIViewRepresentableContext<Spinner>) -> UIActivityIndicatorView {
let spinner = UIActivityIndicatorView(style: style)
spinner.hidesWhenStopped = true
spinner.color = color
return spinner
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<Spinner>) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我应该怎么做才能使变量随着打印而改变但在视图内部改变?我尝试了很多选择,但没有任何效果! 谢谢
答案 0 :(得分:1)
发布您的媒体资源
class GettingData: ObservableObject {
@Published var doneGettingData = false
}
然后观察数据并将该实例传递到MapView
中以供使用,因此请在内部修改该属性
struct ContentView: View {
@ObservedObject var model = GettingData()
var body: some View {
VStack {
MapView(dataGetter: model).edgesIgnoringSafeArea(.top)
Spacer()
Spinner(isAnimating: model.doneGettingData, style: .large, color: .red)
}
}