SwiftUI_visionOS_Note

.sheet() & .fullScreenCover()

Jan 1, 2024
1 min read|
  • We will use .sheet() to create a popup screen
  • .fullScreenCover will cover the full screen.
  • Use environment dismiss value to undo the popup screen.

1. Create a button that toggles the boolean.

import SwiftUI
import RealityKit
import RealityKitContent

struct ContentView: View {
    
    

    @State var showSheet: Bool = false
    var body: some View {
        NavigationStack{
            ZStack{
                 Button(action: {
                    showSheet.toggle()
                }, label: {
                    Text("Button")
                }) 
            }
        }
    }
}
swift

2. Create Second Screen structure

struct SecondScreen: View {
    
    
    
    
    var body: some View {
        NavigationStack (){
            HStack(){
                
                Button(action: {
                 
                }, label: {
                    Image(systemName: "xmark")
                        .font(.headline)
                        .padding()
                        .buttonStyle(.plain)
                }).padding()
                Spacer()
            }
Spacer()
            Text("Happy New Year").font(.extraLargeTitle)
                .frame(depth: 200)
            Spacer()
            
        }
    }
}
swift

3. Add .sheet() under the Content View to present the Second Screen when the button gets clicked.

  • We will add a .sheet() under the button.
  • We bind the showSheet variable to .sheet()
  • and content will be a SecondScreen.

We didn’t assign anything on that “X” button, so we can’t go back to the screen.

Button(...)
	.sheet(isPresented: $showSheet, content: {SecondScreen()})
swift

4. Add dismiss function under Second Screen

  • Add Environement(\.dismiss) var dismiss to create a dismiss function.
  • Add a dismiss inside the button action.
struct SecondScreen: View {
    
    
    
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        NavigationStack (){
            HStack(){
                
                Button(action: {
                    dismiss()
                }, label: {
                    Image(systemName: "xmark")
                        .font(.headline)
                        .padding()
                        .buttonStyle(.plain)
                }).padding()
                Spacer()
            }
Spacer()
            Text("Happy New Year").font(.extraLargeTitle)
                .frame(depth: 200)
            Spacer()
            
        }
    }
}
swift

Someone told me, "you should learn AI instead of VisionOS."

However, I'm interested in building experiences, which is why I'm focusing on MR.