First time posting here I hope I can get some help from code crew!
In my app, Im creating a button view that has two properties, one state property called “pressed” and one var enabled. (Both are bool variables).
In the button action, i toggle the pressed property.
The button gets disabled when enabled that was passed on from parent view is not true.
However, I also want the buttons to be pressed = false when enable is not true.
The solution i came up with was to call button with pressed: false when enabled: false.
However this doesn’t work - i think its because “pressed” is a @State property.
Is there a way to use toggle() without the property being a state property?
Is there a better solution in making the pressed property false when enabled is false?
my button view looks like this:
struct GuitarFretButton: View { @State public var pressed = false
var enabled: Bool
I’m not quite sure what you’re going for. But you can set the pressed property when the View struct appears:
struct GuitarFretButton: View {
@State public var pressed = false
var enabled: Bool
var body: some View {
Button {
pressed.toggle()
} label: {
Image(systemName: pressed == false ? "circle" : "circle.fill")
}
.accentColor(.red)
.disabled(!enabled)
.onAppear {
pressed = enabled
}
}
}
Also, when posting code to these forums, please place three backticks ``` on the line before your code and three backticks ``` on the line after your code so that it will be formatted properly. You can also highlight an entire code block and click the </> button on the toolbar to wrap the block for you.
Thank you i will definitely post code that way next time!
I was able to figure out what to do (used something i learned from calculator app operation lesson from cwc), and i mistakenly was trying to save the pressed property in guitar fret model not view model.
Anyways things are working now and this is what i did o the button view:
struct GuitarFretButton: View {
@EnvironmentObject var userChord:GuitarChordModel
var pressed: Bool
var enabled: Bool
//var fret: Int
//var string: Int
var toggleFunction: () -> ()
// Do not make a @State variable when you want property to take in something and change data
var body: some View {
Button {
//userChord.fretPressed[fret][string].toggle()
toggleFunction()
} label: {
Image(systemName: pressed == false ? "circle" : "circle.fill")
}
.accentColor(.red)
.disabled(!enabled)
}
}