SwiftUI Button

Created At: 2023-02-08 00:13:01 Updated At: 2023-02-08 00:40:17

SwiftUI buttons are not like Flutter buttons. They are also not like widgets. They call it control. So Button is a control in SwiftUI.

Controls enable user interaction with consistent APIs that adapt to their platform and context

Simple Button

Let's go ahead a create a simplest type of button in swiftui. Just put a Button (a control) inside VStack or HStack. Here you go

  VStack {
            Button{
                //your events go here
            }label: {
                //your views go here
            }
        }

In the above case inside label, you may show your view. And that would be your Button name. If you don't want to use label, you can mention the button name like below

        VStack {
            Button("Here"){
                //your events go here
            }
        }

But you won't be able to use Button name if you mention both in label and in the parenthesis of the button. You will get error like below

        VStack {
            Button("Here"){
                //your events go here
            }label: {
                Text("hi")
            }        
        }

Style Button

Once you know how Buttons work in SwiftUI, then it's easy to style them, they are just like other controls or view to style. Just add the below properties tag with Button curly braces.

  1.     .padding()
  2.     .background(.blue)
  3.     .foregroundColor(.white)
  4.     .clipShape(Capsule())

Of course you can add more of the functions and style your button as you want. Now your button may look like this

        VStack {
            Button{
                //your events go here
            }label: {
                 Text("Hello there").font(.system(size: 28))
            }.padding()
                .background(.blue)
                .foregroundColor(.white)
                .clipShape(Capsule())
        }

Here I have added font size to Text() view, so that it looks better.

Comment

Add Reviews