如何在工作表视图上使用不透明的背景色?

时间:2020-09-04 16:43:53

标签: swiftui swift5

我目前正在使用SwiftUI开发应用程序。

我正在寻找某种方法来使“工作表”视图上的背景颜色不透明。

有什么办法吗?


我尝试使用下面的代码执行此操作,我可以使用opacity属性更改颜色,但是在工作表视图下看不到文本(Sheet)...

 I  STORAGE  [initandlisten] exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: ./database/data, terminating
2020-09-04T16:40:42.946+0000 I  NETWORK  [initandlisten] shutdown: going to close listening sockets...
2020-09-04T16:40:42.946+0000 I  -        [initandlisten] Stopping further Flow Control ticket acquisitions.
2020-09-04T16:40:42.946+0000 I  CONTROL  [initandlisten] now exiting
2020-09-04T16:40:42.946+0000 I  CONTROL  [initandlisten] shutting down with code:100

Xcode:版本11.7

Swift:Swift 5

2 个答案:

答案 0 :(得分:7)

使用我一整天都在寻找的来自@Asperi 的很棒的答案,我构建了一个简单的视图修改器,现在可以应用到 .sheet 或 .fullScreenCover 模态视图中并提供透明背景。然后,您可以根据需要为内容设置框架修饰符以适合屏幕,而用户不必知道模态不是自定义大小。

import SwiftUI

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

struct ClearBackgroundViewModifier: ViewModifier {
    
    func body(content: Content) -> some View {
        content
            .background(ClearBackgroundView())
    }
}

extension View {
    func clearModalBackground()->some View {
        self.modifier(ClearBackgroundViewModifier())
    }
}

用法:

.sheet(isPresented: $isPresented) {
            ContentToDisplay()
            .frame(width: 300, height: 400)
            .clearModalBackground()
    }

答案 1 :(得分:3)

您不能使用标准工作表官方API来执行此操作(因为默认情况下每个主机控制器视图都是不透明的),因此您可以创建自定义工作表视图(具有所需的任何功能)或使用运行时解决方法来查找该视图并设置背景清晰。如下所示(仅用于演示

demo

struct DemoView: View {

    @State var isSheet = false

    var body: some View {

        Button(action: {self.isSheet.toggle()}) {
            Text("Sheet")
        }.sheet(isPresented: $isSheet){
            Color.yellow.opacity(0.5)
                .background(BackgroundClearView())
        }
    }
}

struct BackgroundClearView: 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) {}
}
相关问题