在Secondary結構中,@Binding屬性是secondTime,我希望它最初具有來自“父”的值。
但是當我更改此結構中的值時,time父級中的屬性也會更改。有沒有辦法從父級獲取值但防止對值的任何更改回傳到父級?
struct ContentView: View {
@State var time: String = "";
var body: some View {
VStack {
Text("it is: \(time)")
Secondary(secondTime: $time)
Button("Change time") {
time = "2 poclock"
}
}
}
}
struct Secondary: View {
@Binding var secondTime: String;
var body: some View {
Text("secondary time is \(secondTime)")
Button("Change time again from Secondary View") {
secondTime = "3 oclock"
}
}
}
uj5u.com熱心網友回復:
在Secondary使用:
@State var secondTime: String
并在ContentView使用中:
Secondary(secondTime: time)
不是 $time
編輯1:
如果您想單擊按鈕ContentView更改兩個視圖,但Secondary只更改自身,請嘗試以下方法:
struct Secondary: View {
@Binding var secondTime: String
@State var localTime: String = ""
var body: some View {
Text("Secondary time is \(localTime)") // <--- here
.onChange(of: secondTime) { newval in // <--- here
localTime = newval // <--- here
}
Button("Change time again from Secondary View") {
localTime = "3 oclock " String(Int.random(in: 1..<100)) // <-- to show changes
}
}
}
struct ContentView: View {
@State var time: String = ""
var body: some View {
VStack (spacing: 55) {
Text("ContentView it is: \(time)")
Secondary(secondTime: $time)
Button("Change time") {
time = "2 oclock " String(Int.random(in: 1..<100)) // <-- to show changes
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368987.html
上一篇:SwiftUI中的“.colorName”和“Color.colorName”有什么區別?如果它們相同,為什么會顯示兩個輸出?[復制]
