Saturday, November 21, 2026
HomeiOS Developmentios - SwiftUI: Altering a non-public var with a slider

ios – SwiftUI: Altering a non-public var with a slider

[ad_1]

Property observers will not work with SwiftUI @State variables.

Use .onChange(of:) to behave upon modifications to tempVar:

struct MyView: View {
    @State var myStructToEdit = MyStruct()
    @State var tempVar: Double = 0.0

    var physique: some View {
        VStack {
            Textual content(String(tempVar))
            Textual content(String(myStructToEdit.getMyVar()))
            Slider(worth: $tempVar, in: 1.0...20.0, step: 1.0)
                .onChange(of: tempVar) { worth in
                    myStructToEdit.setMyVar(newVal: Float(worth))
                }
        }
    }
}

Use Binding(get:set:) to straight set and get the worth in your struct:

You do not want tempVar. You possibly can straight set and get the worth to and out of your struct.

struct ContentView: View {
    @State var myStructToEdit = MyStruct()

    var physique: some View {
        VStack {
            Textual content(String(myStructToEdit.getMyVar()))
            Slider(worth: Binding(get: {
                myStructToEdit.getMyVar()
            }, set: { worth in
                myStructToEdit.setMyVar(newVal: worth)
            }), in: 1.0...20.0, step: 1.0)
        }
    }
}

or assign the Binding to a let to make it cleaner:

struct ContentView: View {
    @State var myStructToEdit = MyStruct()

    var physique: some View {
        let myVarBinding = Binding(
            get: { myStructToEdit.getMyVar() },
            set: { worth in myStructToEdit.setMyVar(newVal: worth) }
        )
        
        VStack {
            Textual content(String(myStructToEdit.getMyVar()))
            Slider(worth: myVarBinding, in: 1.0...20.0, step: 1.0)
        }
    }
}

Be aware: Since myVarBinding is already a binding, you do not want to make use of a $ to show it right into a binding.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments