SwiftUI中如何修改Sheet弹出视图后的背景样式?
修改SwiftUI Sheet弹出后的背景透明度/颜色
你可以通过以下两种方式修改Sheet弹出视图后方的背景遮罩(即你截图中标注的红色区域):
iOS 16+ 原生简洁方案
iOS16及以上版本提供了presentationBackground修饰符,可直接设置背景遮罩的颜色和透明度:
@State var presentElement: Bool = false @State private var frameSize: CGFloat = 0 // 需先声明frameSize变量 var body: some View { Text("Present el") .onTapGesture { presentElement = true } .sheet(isPresented: $presentElement) { NotifActionModal() .background { GeometryReader { geometry in Color.clear .onAppear { frameSize = geometry.size.height } } } .presentationDetents([.height(frameSize)]) // 设置背景遮罩:黑色半透明,可自定义颜色和透明度 .presentationBackground(Color.black.opacity(0.5)) } }
直接替换Color.black.opacity(0.5)为你需要的颜色即可,比如Color.red.opacity(0.3)实现红色半透明效果。
iOS 15及以下兼容方案
如果需要适配iOS15及更早版本,可通过UIKit扩展修改Sheet的背景:
首先添加UIViewController扩展:
extension UIViewController { func setSheetBackgroundOpacity(_ opacity: CGFloat, color: UIColor = .black) { guard let sheetPresentationController = sheetPresentationController else { return } sheetPresentationController.backgroundColor = color.withAlphaComponent(opacity) } }
然后在SwiftUI视图中调用:
@State var presentElement: Bool = false @State private var frameSize: CGFloat = 0 var body: some View { Text("Present el") .onTapGesture { presentElement = true } .sheet(isPresented: $presentElement) { NotifActionModal() .background { GeometryReader { geometry in Color.clear .onAppear { frameSize = geometry.size.height } } } .presentationDetents([.height(frameSize)]) .onAppear { UIApplication.shared.windows.first?.rootViewController?.presentedViewController?.setSheetBackgroundOpacity(0.5, color: .black) } } }
注意事项
- 若使用
presentationBackground,需确保项目部署目标为iOS16+; - 原代码中
frameSize需声明为@State变量,否则会出现编译错误; - 自定义颜色时,可使用
Color(uiColor: .yourUIColor)适配更多颜色需求。
内容的提问来源于stack exchange,提问作者neo
相关产品推荐
相关产品推荐

