Button in SwiftUI

Lets learn how to work with a Button in SwiftUI.

Let me explain the code snippet:
1. Two private variables, one is buttonClicked which is a Bool that will toggle on button click action and the other is textOnLabel is a String with a default as BLACK.
2. In body I have a VStack with spacing 50, it will add a spacing of 50 between UIControls added inside the stack.
3. Inside this VStack; I wanted to have a Text (to display the Background Color of Button) and a Button.
4. Inside Button's action closure I toggled the bool value of var buttonClicked and made a call to method buttonAction().
5. Inside this buttonAction method I just changed the text of textOnLabel based on the buttonClicked bool value.
6. To make Button UI better I added padding, background color, foreground color and cornerradius to it.


struct ContentView: View {
    @State private var buttonClicked = false
    @State private var textOnLabel: String = "BLACK"
    var body: some View {
        VStack(spacing: 50) {
            Text(textOnLabel)
                .font(.largeTitle)
                .foregroundColor(.green)
            Button(action: {
                self.buttonClicked.toggle()
                self.buttonAction()
            }) {
                Text("HIT ME")
                    .font(.largeTitle)
                    
            }
            .padding(.init(top: 10, leading: 20, bottom: 10, trailing: 20))
            .background(self.buttonClicked == true ? Color.orange : Color.black)
            .foregroundColor(self.buttonClicked == true ? Color.black : Color.white)
            .cornerRadius(10)
        }
    }
    
    func buttonAction() {
        if buttonClicked == true {
            textOnLabel = "ORANGE"
        } else {
            textOnLabel = "BLACK"
        }
    }
}


Output:

 


Another simple code snippet to check how Button works:

Code Snippet:
struct ContentView: View {
    @State var myName = "SUMERA"
    var body: some View {
        VStack (spacing: 50) {
            Text(myName)
                .font(.largeTitle)
                .foregroundColor(.green)
            Button(action: {
                self.myName = (self.myName == "SUMERA") ? "AMARA" : "SUMERA"
            }) {
                Text("TOGGLE NAMES")
                    .padding(.all)
                    .font(.headline)
                    .foregroundColor(.white)
                    .background(Color.red)
                    .cornerRadius(10)
            }
        }
    }
}

Output:
 

Comments

Popular posts from this blog

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

payUmoney Payment Gateway Integration in iOS App (Objective C)

Check Internet Connectivity Using AFNetworking 2.0