[英]How to ignore SwiftUI modal background, or make modal background clear/transparent?
[英]how to make the modal view with a transparent background in SwiftUI?
我正在使用协调器模式,在程序集中创建视图
let view = UIHostingController(rootView: swiftuiview)
view.view.backgroundColor = .clear
内部路由器只呈现这个 UIHostingController
module.modalPresentationStyle = .overCurrentContext
navigationController.present(module, animated: animated, completion: nil)
如果您想从 UIKit 项目模糊 SwiftUI 的背景,并且可能将 SwiftUI 视图用于模态视图,那么我最近遇到了同样的问题,并创建了一个 UIViewController,它采用 UIHostController(基本上是 UIViewController),然后更改 HostingController 视图的 alpha,在后面放置一个模糊并将其呈现给父视图。
我已经创建了一个包含文件的要点供公众使用https://gist.github.com/Ash-Bash/93fd55d89c1e36f592d3868f6b29b259
这是工作示例:
// Initialises BlurredHostingController
var blurredHostingController = BlurredHostingController()
// Sets the Hosting View for the SwiftUI View Logic
blurredHostingController.hostingController = UIHostingController(rootView: ContentView())
// Blur Tweaks for blurredHostingController
blurredHostingController.blurEffect = .systemMaterial
blurredHostingController.translucentEffect = .ultrathin
// Presents View Controller as a Modal View Controller
self.present(blurredHostingController animated: true, completion: nil)
展示:
let rootView = Text("Hello world")
let controller = UIHostingController(rootView: rootView)
controller.view.backgroundColor = .clear
UIApplication.shared.windows.first?.rootViewController?.present(controller, animated: true)
解雇:
UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true)
我没有找到理想的方法,但我有一个解决方法。
因此,为了以模态方式呈现视图,您可以采用 ZStack 并将其中的多个视图分组,并使用像这样的 @State 变量来处理它。
在这里,我为视图提供了背景颜色,以便更好地解释。
struct ContentView : View {
@State private var showModally = false
var body : some View {
ZStack {
Color.red
VStack {
Button(action: {
withAnimation{
self.showModally = true
}
}) {
Text("Push Modally")
}
}
ModalView(show: $showModally)
.offset(y: self.showModally ? 0 : UIScreen.main.bounds.height)
.animation(.spring())
}
}
}
struct ModalView: View {
@Binding var show : Bool
var body: some View {
VStack {
Spacer()
VStack {
Color.white
}
.frame(height : 400)
.cornerRadius(10)
.padding(.horizontal)
}
.background(Color.clear)
.onTapGesture {
self.show = false
}
}
}
在这种情况下,模态视图将模态地呈现在内容视图上,并通过点击关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.