How to create a basic button in SwiftUI

 There are various ways to create a button in SwiftUI, let's start with a button that consists of text:

Button("Print") {

print("Button pressed")

}

Here, we specify the text for the button and inside the curly braces is the code we want to run when the button is press. In this case we print "Button pressed" but you can put any action you want there. The button will appear blue by default but you can change its colour with a modifier:

Button("Print") {

print("Button pressed")

}.foregroundColor(.red)


You may have noticed in iOS buttons don't have to be text, but they can consist of a range of different views to customise their look. For example you can give the button a background like this:

Button(action: { print("Button pressed")}, label: {

Text("Print")

.foregroundColor(.white)

.padding()

.background(Color.blue)

.cornerRadius(5)

}


Buttons don't require text either, they could be an image or shape too:

Button(action: { print("Button pressed")}, label: {

Image("printer")

}


Button(action: { print("Button pressed")}, label: {

Rectangle()

.frame(width: 100, height: 100)

.foregroundColor(Color.pink)

}

Comments

Popular posts from this blog

How to show placeholder text in a WPF TextBox in C# and VB

How to enable dark title bar in WPF and Windows Forms/WinForms apps in C# and VB

How to use modern icons in XAML in WPF on Windows 10 and 11

How to change the colour of a WPF or Windows Forms/WinForms title bar in Windows 11 in C# and VB

Microsoft WebView2: How to check if the WebView2 runtime is installed in C# and VB