SwiftUI 更改工作表背景

Dar*_*isa 5 swiftui

如何更改模态表背景?例如,如果我有:

  Button(action: showAdditionalOptions) {
      Image(systemName: "ellipsis")
        .font(.system(size: 20))
        .foregroundColor(Color.white)
    }
    .onTapGesture { showAdditionalOptions() }
    .fullScreenCover(isPresented: $isShowingAdditionalOptions) {
      AdditionalActions()
        .background(Color.black.opacity(0.2))
    }
Run Code Online (Sandbox Code Playgroud)

我想要达到的效果是一种模糊效果,当呈现一张纸时,其背景是模糊的并且部分透明。但是我无法更改工作表的背景。我只能修改工作表的内容背景。有没有办法将背景应用到工作表本身?

Pau*_*l B 3

从 iOS 16.4 开始,可以将.presentationBackground(_ style: S)与颜色和模糊(材质类型)一起使用。

struct ContentView: View {
    @State private var isPresented = false
    var body: some View {
        Button(action: {
            isPresented.toggle()
        }, label: {
            Label("Sheet", systemImage: "list.bullet.rectangle.portrait")
        })
        .fullScreenCover(isPresented: $isPresented) {
            HStack {
                Text("Detail")
                Button(action: {
                    isPresented =  false
                }, label: {
                    Label("Dismiss", systemImage: "xmark.circle.fill")
                })
            }
            .background(.yellow)
            .presentationBackground(.clear)
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

为了支持以前的版本而不需要混乱的代码,您可以像这样向后移植此功能。可以完全复制.presentationBackground(_ style: S)签名调用UIVisualEffectView(effect:),但为了简单起见,我将提供纯颜色版本。

struct PresentationBackgroundView: UIViewRepresentable {
    
    var presentationBackgroundColor = Color.clear

    @MainActor
    private static var backgroundColor: UIColor?
    
    func makeUIView(context: Context) -> UIView {
        
        class DummyView: UIView {
            var presentationBackgroundColor = UIColor.clear
            
            override func didMoveToSuperview() {
                super.didMoveToSuperview()
                superview?.superview?.backgroundColor = presentationBackgroundColor
            }
        }
        
        let presentationBackgroundUIColor = UIColor(presentationBackgroundColor)
        let dummyView = DummyView()
        dummyView.presentationBackgroundColor = presentationBackgroundUIColor
        
        Task {
            Self.backgroundColor = dummyView.superview?.superview?.backgroundColor
            dummyView.superview?.superview?.backgroundColor = presentationBackgroundUIColor
        }
        
        return dummyView
    }
    
    static func dismantleUIView(_ uiView: UIView, coordinator: ()) {
        uiView.superview?.superview?.backgroundColor = Self.backgroundColor
    }
    
    func updateUIView(_ uiView: UIView, context: Context) { /* likely there is need to update */}
}

extension View {
    func presentationBackground(_ color: Color = .clear) -> some View {
        self.background(PresentationBackgroundView(presentationBackgroundColor: color))
    }
}
Run Code Online (Sandbox Code Playgroud)