SwiftUI Reference

SwiftUI Buttons

SwiftUI Button

The default UI for a button.

Button(action: {}) {
    Text(“Text Button”)
}

SwiftUI Button Actions

Run One Line of Code

Button(action: {print(“Thanks for reading.”)}) {
        Text(“Run one line of code”)
}

Run Multiple Lines of Code

Button(action: {
        print(“Thanks for reading.”)
        print(“Look this is a second line of code!”)
})
{
        Text(“Run one line of code”)
}

Calling a function

var body: some View {
        HStack {
                Button(action: {functionName()}) {
                         Text(Call Function)
                  }
            }
       }
}
func functionName(){
        print(Running Function)
}

Button Text Colors

Use the .foregroundColor property to modify the color of the button text. 

Button(action: {}) {
    Text(Blue Button)
       .foregroundColor(Color.blue)
}
Button(action: {}) {
    Text(Red Button)
        .foregroundColor(Color.red)
}
Button(action: {}) {
    Text(Green Button)
        .foregroundColor(Color.green)
}
Button(action: {}) {
    Text(Black Button)
        .foregroundColor(Color.black)
}

Button with Background

Button(action: {print(Thanks for using Swiftly Dierkes)}) {
    Text(Print Something)
    .padding(.horizontal, 20.0 )
    .padding(.vertical, 10.0)
    .foregroundColor(Color.white)
    .background(Color.blue)
    .cornerRadius(5)
}

Button Corner Radius

Use the .cornerRadius property to modify the corner radius

Button(action: {}) {
    Text(“4”)
   .padding()
  .foregroundColor(Color.white)
  .background(Color.blue)
  .cornerRadius(4)
}
Button(action: {}) {
    Text(“8”)
    .padding()
    .foregroundColor(Color.white)
    .background(Color.red)
    .cornerRadius(8)
}
Button(action: {}) {
    Text(“12”)
    .padding()
    .foregroundColor(Color.white)
    .background(Color.green)
    .cornerRadius(12)
}

Disabled Button

Use the .disabled property to disable and enable a button.

Button(action: {}) {
    Text(Normal Button)
}
Button(action: {}) {
    Text(Disabled Button)
    .disabled(true)
}

Made with ❤ By Mason Dierkes

Close Menu