我需要从视图组件内的按钮推送模态视图,但应该只覆盖屏幕高度的下半部分,上半部分是半透明背景(黑色,不透明度 30%)。在全屏覆盖视图构建器中设置最顶层视图的不透明度不起作用。任何帮助,将不胜感激。
struct ContentView: View {
@State var present: Bool = false
var body: some View {
VStack(spacing: 20) {
Button(action: {
present = true
}, label: {
Text("spawn translucent modal")
})
.fullScreenCover(isPresented: $present) {
VStack(spacing: 20) {
Spacer()
.frame(maxWidth: .infinity, minHeight: 100)
.background(Color.black)
.opacity(0.3)
Text("modal")
}
.background(Color.clear)
}
Text("some content")
Text("some more content")
}
}
}
可接受的解决方案有效,但并不理想,因为它需要遍历和猜测视图层次结构。
更可靠的选择是使用UIViewControllerRepresentable
代替UIViewRepresentable
,这样就可以直接访问父控制器了。
.fullScreenCover(isPresented: $present) {
VStack {
Text("modal")
}
.background(Background()) // << helper !!
}
struct Background: UIViewControllerRepresentable {
public func makeUIViewController(context: UIViewControllerRepresentableContext<Background>) -> UIViewController {
return Controller()
}
public func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<Background>) {
}
class Controller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
}
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
parent?.view?.backgroundColor = .clear
parent?.modalPresentationStyle = .overCurrentContext
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)