ios – SwiftUI: Altering a personal var with a slider

[ad_1]

I’ve a personal variable in a struct which I can solely entry utilizing a setter and getter. I need to change this variable utilizing a slider, so I’m trying to bind a unique var with this var utilizing willSet:

struct MyStruct {
    personal var myVar: Float? = nil
    mutating func setMyVar(newVal: Float) {
        if (SomeCondition) { // at all times true when the slider is in use
            myVar = newVal
        } else {
            // stuff
        }
    }
    func getMyVar() -> Float {
        myVar == nil ? 0.0 : myVar!
    }
}

struct MyView: View {
    @State var myStructToEdit = MyStruct()
    @State var tempVar: Double = 0.0 {
        willSet {
            myStructToEdit.setMyVar(newVal: Float(newValue))
        }
    }
    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)
        }
    }
}

Because the slider strikes, tempVar adjustments however MyVar does not. What’s the right approach to obtain this binding?

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *