Multiple sheets in SwiftUI using subviews

Published by malhal on

If you need to show multiple sheets in SwiftUI it is best to use the framework features to your advantage. Rather than try to abstract the problem into a generic coordinator object, which you then have to unbundle again to customise each circumstance, you can simply create multiple small subview value types. SwiftUI modifiers can be applied anywhere in the hierarchy and often can have multiple of the same kind. This allows customisation to be built directly into the View structs when needed and also makes for tighter invalidation. The example below is when we want multiple buttons to show different sheets and the solution is to put each Button into its own subview.

struct ArticlesView: View {
    var body: some View {
        VStack {
            AddArticleButton()
            EditArticleButton()
            ArticleCategoryButton()
        }
        .padding()
        .frame(width: 400, height: 300)
    }
}
    
struct AddArticleButton: View {
    @State var isPresented = false
    var body: some View {
        Button("Add Article") {
            isPresented.toggle()
        }
        .sheet(isPresented: $isPresented) {
            AddArticleView()
        }
    }
}
    
struct EditArticleButton: View {
    @State var isPresented = false
    var body: some View {
        Button("Edit Article") {
            isPresented.toggle()
        }
        .sheet(isPresented: $isPresented) {
            EditArticleView()
        }
    }
}
    
struct ArticleCategoryButton: View {
    @State var isPresented = false
    var body: some View {
        Button("Article Categories") {
            isPresented.toggle()
        }
        .sheet(isPresented: $isPresented) {
            ArticleCategoryView()
        }
    }
}

I was inspired to write this after reading Sheets in SwiftUI explained with code examples that took the coordinator object approach and I highly recommend you subscribe to his feed for more inspiring articles.

Categories: SwiftUI