Search code examples
swiftuiwatchkitwatchosmodal-sheet

SwiftUI image in modal sheets for Apple Watch


I would like to create a modal sheets with an image in the body, like in Human Interface Guidelines. Could you please give me an example?

enter image description here

https://developer.apple.com/design/human-interface-guidelines/watchos/interaction/modality/


Solution

  • The following code basically recreates the example screenshot from above:

    import SwiftUI
    
    struct ModalView: View {
        @Binding var isPresented: Bool
        
        var body: some View {
            VStack {
                Image(systemName: "headphones")
                    .font(.system(size: 30))
    
                Text("To play audio, connect Bluetooth headphones to your Apple Watch.")
                    .font(.footnote)
                    .multilineTextAlignment(.center)
            }
            .opacity(0.8)
            .padding(10)
    
            Spacer()
    
            Button("Connect a Device") {
                isPresented.toggle()
            }.padding(.horizontal)
        }
    }
    
    struct TestView: View {
        @State private var isPresentingModalView = false
        
        var body: some View {
            Button("Connect") {
                isPresentingModalView.toggle()
            }
            .fullScreenCover(isPresented: $isPresentingModalView) {
                ModalView(isPresented: $isPresentingModalView)
            }
        }
    }
    
    struct TestView_Previews: PreviewProvider {
        static var previews: some View {
            TestView()
        }
    }
    
    

    Result:

    enter image description here See docs: https://developer.apple.com/documentation/swiftui/view/fullscreencover(ispresented:ondismiss:content:)