Learn iOS Programming
Butttons are one of the most used user interface elements in SwiftUI. A Basic button is defined as follows.
1 2 3 |
Button(“Delete”){ //Text on button print(“Deleted”) //Action inside closure } |
In above code, Text on button is defined in brackets as “Delete”. Action to be executed after button press is defined in parenthesis.
Button with Function
When a separate function is created for button action, button is defined as follows.
1 2 3 4 5 |
Button(“Delete”, action: executeDelete) fun executeDelete() { print(“Deleted”) } |
Assigning Roles to Buttons
Buttons can be assigned roles to change their appearance as per role. Example is destructive role such as delete. In this case, button is shown in red color.
1 |
Button(“Delete”, role: .destructive, action: executeDelete) |
Adding Styles to Buttons
Styles can be added to buttons as modifiers.
1 2 3 |
Button(“Delete”, action: executeDelete) {} .buttonStyle(.bordered) // OR .buttonStyle(.borderedProminent) // Filled button |
Adding Tint to Buttons
Color of button can be changed using tint modifier as follows.
1 2 3 |
Button(“Delete”, action: executeDelete) {} .buttonStyle(.borderedProminent) // Filled button .tint(.mint) |
Button with Image Icon
Icons can be added to button using trailing closures like label.
1 2 3 4 5 |
Button{ print(“Deleted”) } label: { Label(“Deleted”, systemImage: “pencil”) } |