Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

swift - I want to make the button inactive until the conditions are met SwiftUI

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?

question from:https://stackoverflow.com/questions/65845606/i-want-to-make-the-button-inactive-until-the-conditions-are-met-swiftui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...