SwiftUI - Basic Components

Since Apple introduced its new SwiftUI framework in 2019, developers have quickly started migrating to it as it offers a straightforward and powerful medium to create app interfaces that work seamlessly on iOS, tvOS, macOS, and watchOS.

In this article, we will be discussing some basic UI components offered by SwiftUI and their usage along with an example for each of them so that we have a starting point for our SwiftUI journey.

Text

This is the most basic view that renders either single or multiple lines of text. Different modifiers allow the text to be styled in different ways.

Text("Hi! I am some text. Below are some ways I can be styled.")

Text("I am bold").bold()

Text("I am italic").italic()

Text("I am underlined").underline()

Text("I am first text.").bold() + Text("I am second text.").italic()

Image

This is a view that renders an image. Images can be resized and styled in various ways using SwiftUI modifiers. Supported image types include PNG, JPEG, HEIC, and more.


Image(systemName: "clock.fill").foregroundColor(.indigo)
Image("asset_name").resizable().aspectRatio(contentMode: .fit)

Button

A view that performs an action when it is pressed by the user.


Button(
    action: {
        //Handle button tap
    },
    label: { Text("I am a plain button") }
).padding()

Button("I am a plain button with a simpler syntax"){
    //Handle button tap
}

Button(
    action: {
        //Handle button tap
    },
    label: { Text("I am a plain button but disabled :(") }
).padding().disabled(true)



Button(
    action: {
        //Handle button tap
    },
    label: {
    Image(systemName: "info")
    Text("am a")
    Text("fancy").italic()
    Text("button")
})
.foregroundColor(.white)
.padding()
.background(.orange)
.cornerRadius(40)

Conclusion

In this article, we discussed a few of the most basic components that account for the fundamental building blocks of your SwiftUI app. You can create beautiful interfaces with the use of only these simple components. However, you might need to create some complex interfaces when your app grows and SwiftUI provides us with tools for that as well. We will be discussing these tools in the upcoming blogs. So, stay tuned!

Harsh Siriah

Harsh Siriah

Hi, I'm Harsh! A geek with a love for dogs & mobiles.
Pune, India