Reputation: 137
I want to make a button inactive until the conditions are met (While in my checkbox are inactive)
How to do it in SwiftUI
struct CheckBoxView: View {
@State var isChecked:Bool = false
func toggle() {isChecked = !isChecked}
var body: some View {
Button(action: toggle){
HStack{
Image(systemName: isChecked ? "checkmark.square": "square")
}
}
}
}
struct SwiftUIViewTest: View {
var cb = CheckBoxView()
var body: some View {
VStack {
HStack {
cb
Text("Activate the checkbox")
}
.padding()
Button(action: {
// ...
}) {
Text("Activate")
}
.frame(width: 100, height: 50, alignment: .center)
.foregroundColor(.white)
.background(Color.orange)
}
}
}
How do I refer to the button? And where is it better to write logic for this?
Upvotes: 0
Views: 101
Reputation: 18914
Use @Binding
and @State
struct CheckBoxView: View {
@Binding var isChecked: Bool //<-- Here
func toggle() {isChecked = !isChecked}
var body: some View {
Button(action: toggle){
HStack{
Image(systemName: isChecked ? "checkmark.square": "square")
}
}
}
}
struct ContentView: View {
@State private var isActivate: Bool = false //<- Here
var body: some View {
VStack {
HStack {
CheckBoxView(isChecked: $isActivate)
Text("Activate the checkbox")
}
.padding()
Button(action: {
// ...
}) {
Text(isActivate ? "Activate" : "Disable")
}
.disabled(!isActivate)
.frame(width: 100, height: 50, alignment: .center)
.foregroundColor(.white)
.background(Color.orange)
}
}
}
Upvotes: 1