0
Follow
2
View

SwiftUI: Preventing binding value from passing back up?

david1202 注册会员
2023-01-26 02:39

In Secondary use:

@State var secondTime: String 

and in ContentView use:

Secondary(secondTime: time)

not $time

EDIT1:

If you want to click the button in ContentView to change both views, but Secondary only changes itself, then try this approach:

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
                }
            }
        }
    }

About the Author

Question Info

Publish Time
2023-01-26 02:39
Update Time
2023-01-26 02:39