SwiftUI - Advanced Components Part 3

We have already taken a look at several advanced components in earlier posts from the series on SwiftUI. In this article, we continue our journey and check out some more SwiftUI components. Furthermore, this article will include the implementation of states. If you are unfamiliar with that concept, you can read about it here.

Alerts

A container that presents data as an alert. The container is rendered on top of all the other UI elements and it might interrupt ongoing interactions by the user. Alerts can be used to display important information that might need urgent attention from the user, such as errors or request failures.

@State var isError: Bool = false

Button("Show Alert") {
    self.isError = true
}.alert(isPresented: $isError, content: {
    Alert(
        title: Text("This is an alert"),
        message: Text("Alert message body"),
        dismissButton: .default(Text("Close alert")))
})

Modals

Presents a sheet containing data on top of a view. Modals can be shown with the help of a boolean passed in the isPresented attribute of the sheet modifier in SwiftUI. Modals can be used to display information like filters, product details, etc.

@State var isModal: Bool = false
    
var modal: some View {
    CustomView(text: "Hi modal!")
}

Button("Show modal") {
    self.isModal = true
}.sheet(isPresented: $isModal, content: {
    self.modal
})

ActionSheet

A container that displays multiple options for the user to choose from. It is recommended to use an action sheet when you want the user to make a choice between two or more options, in response to their own action. You can perform different functions on the selection of different options.

@State var isSheet: Bool = false

@State var reaction: String = ""


var actionSheet: ActionSheet {
    ActionSheet(
        title: Text("This is an action sheet"),
        message: Text("Are you sure you understand this concept?"),
        buttons: [
            .default(Text("Yes"), action: {
                reaction = ":)"
            }),
            .destructive(Text("No"), action: {
                reaction = ":("
            })
        ]
    )
}

Button("Action Sheet") {
    self.isSheet = true
}.actionSheet(isPresented: $isSheet, content: {
    self.actionSheet
})

Divider()

Text("\(reaction)")

Conclusion

This article discussed the three ways you can use containers that are drawn on top of other content to deliver information to the user. Alerts, modals, and action sheets are highly customizable and can adapt to your use case in most situations.

We conclude the series on SwiftUI basic and advanced components. You can check out all the blogs from this series here. In the future, we will continue looking at different concepts in SwiftUI and iOS mobile app development in general.

So, stay tuned!

Harsh Siriah

Harsh Siriah

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