MultiModal

2.1.0

Use multiple .sheet, .alert, etc. modifiers in the same SwiftUI View
davdroman/MultiModal

What's New

2.1.0

2021-09-28T16:01:55Z
  • Added compatibility with macOS, tvOS, watchOS #6
  • Replaced demo project with demo Xcode Playground #7

MultiModal

CI

Introduction

By default, SwiftUI views with multiple modal modifiers (e.g. .sheet, .alert) in the same body will only use the last one in the chain of modifiers and ignore all previous ones.

struct NoMultiModalDemoView: View {
    @State var sheetAPresented = false
    @State var sheetBPresented = false
    @State var sheetCPresented = false

    var body: some View {
        VStack(spacing: 20) {
            Button("Sheet A") { sheetAPresented = true }
            Button("Sheet B") { sheetBPresented = true }
            Button("Sheet C") { sheetCPresented = true }
        }
        .sheet(isPresented: $sheetAPresented) { Text("Sheet A") } // does not work
        .sheet(isPresented: $sheetBPresented) { Text("Sheet B") } // does not work
        .sheet(isPresented: $sheetCPresented) { Text("Sheet C") } // works
    }
}

MultiModal brings a .multiModal modifier to declare multiple modal modifiers in the same view body.

struct MultiModalDemoView: View {
    @State var sheetAPresented = false
    @State var sheetBPresented = false
    @State var sheetCPresented = false

    var body: some View {
        VStack(spacing: 20) {
            Button("Sheet A") { sheetAPresented = true }
            Button("Sheet B") { sheetBPresented = true }
            Button("Sheet C") { sheetCPresented = true }
        }
        .multiModal {
            $0.sheet(isPresented: $sheetAPresented) { Text("Sheet A") } // works
            $0.sheet(isPresented: $sheetBPresented) { Text("Sheet B") } // works
            $0.sheet(isPresented: $sheetCPresented) { Text("Sheet C") } // works
        }
    }
}

Try it out!

MultiModal supports Arena to effortlessly test this library in a playground before you decide to take it for a spin in your own project.

Simply install Arena and run arena davdroman/MultiModal --platform ios in your terminal.

Alternatively, a standalone demo Xcode Playground is also provided in this package.

Disclaimer

MultiModal does not enable "nested" modals; it just enables multiple modals appearing within a view body one at a time. For this reason, it's recommended that your modal presentation be dependant on a source of truth that ensures only one of them is presented at any given time.

Hopefully Apple will introduce support for multiple modals in a future iteration of SwiftUI, rendering this library unnecessary.

Description

  • Swift Tools 5.1.0
View More Packages from this Author

Dependencies

  • None
Last updated: Fri Oct 15 2021 17:10:28 GMT-0500 (GMT-05:00)