【发布时间】:2020-05-11 21:27:20
【问题描述】:
在下面的代码中,变量“yourVariable”是在一个结构中定义的。然后我使用滑块更改“yourVariable”,但是当我尝试在 SecondView 中使用变量时,它使用的是原始变量而不是更新的变量。我被告知我需要更新房产,我应该这样做吗?如果是,请有人解释原因。
import SwiftUI
import PlaygroundSupport
struct MyVariables {
static var yourVariable = 500000.0
}
struct SecondView : View {
@Environment(\.presentationMode) var presentationMode
var string = MyVariables.yourVariable
var body: some View {
VStack {Button("\(string)") {
self.presentationMode.wrappedValue.dismiss()
}
}
}
}
struct ContentView : View {
@State private var showingSheet = false
@State public var step = 0
@State public var text = ""
@State public var slide = 20.0
@State public var slidetwo = MyVariables.yourVariable + 60000
var r0 : Double {
rvalues[(wearingMaskToggle ? 1:0) + (washingHandsToggle ? 2:0) + (quarantineToggle ? 8:0) + (coverMouthToggle ? 4:0)]
}
@State private var rvalues = [6.5, 6.1, 5.3, 4.8, 4.2, 3.5, 3.1, 2.9, 1.75, 1.5, 1.2, 1.0, 0.92, 0.82, 0.75, 0.7]
var body: some View {
ZStack {
Color.gray
.edgesIgnoringSafeArea(.all)
VStack {
HStack {
Button(action: {
if self.slidetwo > 10000{
self.slidetwo -= 1000 //When rand = 10050, it still works
}
}, label: {
Image(systemName: "minus")
})
Slider(value: $slidetwo, in: 10000...1000000, step: 1000)
.padding(20)
.accentColor(Color.green)
Button(action: {
if self.slidetwo < 1000000{
self.slidetwo += 1000
}
}, label: {
Image(systemName: "plus")
})
}.foregroundColor(Color.green) .padding(.horizontal, 100)
}
Text("Initial Population: \(Int(slidetwo))")
Button("Show Sheet") {
self.showingSheet.toggle()
}
.sheet(isPresented: $showingSheet) {
SecondView()
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
【问题讨论】:
-
你在哪里改变 yourVariable 的值?
标签: swift swiftui swift-playground