「SwiftUI」常用的sheet/fullScreenCover

Posted by Jiaolong on 2022/04/07

sheet

Example

struct ExampleView: View {
    @State private var showSheet = false

    var body: some View {
        Button("Open sesame 📬") {
            showSheet = true
        }
        .sheet(isPresented: $showSheet,
               onDismiss: { print("dismissed!") },
               content: { ExampleSheet() })
    }
}

struct ExampleSheet: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("CLOSE 📪") {
            presentationMode.wrappedValue.dismiss()
        }
    }
}

A gif displaying a view with a button reading "Open sesame 📬" which triggers the presentation of a sheet with a button reading "CLOSE 📪"; upon dismissal of the sheet with the close button, the console prints "dismissed!" and the sheet slides back down until hidden.

fullScreenCover

Example

struct ExampleView: View {
    @State private var showCover: Bool = false

    var body: some View {
        Button("Open sesame 📬") {
            showCover = true
        }
        .fullScreenCover(isPresented: $showCover,
            onDismiss: { print("dismissed!") },
            content: { ExampleSheet() })
    }
}

struct ExampleSheet: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        ZStack {
            Button("CLOSE 📪") {
                presentationMode.wrappedValue.dismiss()
            }
        }
    }
}


A gif displaying a view with a button reading "Open sesame 📬" which triggers the presentation of a full screen cover with a button reading "CLOSE 📪"; upon dismissal of the sheet with the close button, the console prints "dismissed!" and the sheet slides back down until hidden.

设置透明背景

VStack{
  	//content
}
.background(BackgroundCleanerView())		//	<--- there

struct BackgroundCleanerView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        DispatchQueue.main.async {
            view.superview?.superview?.backgroundColor = .clear
        }
        return view
    }
    func updateUIView(_ uiView: UIView, context: Context) {}
}

参考链接: