我正在使用协调者模式,在组装中创建视图。
let view = UIHostingController(rootView: swiftuiview)
view.view.backgroundColor = .clear
在路由器内只需呈现此UIHostingController
module.modalPresentationStyle = .overCurrentContext
navigationController.present(module, animated: animated, completion: nil)
// 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
}
}
}
在此情况下,模态视图将以模态方式呈现在内容视图上方,并通过轻触来关闭。
iOS 16.4+
您可以使用新的修饰符来显示具有透明背景的全屏模态:
使用形状样式设置封闭表单的演示背景。
以下是一个例子:
struct ContentView: View {
@State private var showSettings = false
var body: some View {
Button("View Settings") {
showSettings = true
}
.fullScreenCover(isPresented: $showSettings) {
SettingsView()
.presentationBackground(.thickMaterial) // <-- this
}
}
}
if segue.identifier == "AnotherView", let hostingController = segue.destination as? HostingSwiftUIView {
hostingController.modalPresentationStyle = .formSheet
hostingController.preferredContentSize = CGSize(width: 700, height: 300) // customise as per View
hostingController.rootView = AnyView(AnotherView())
}
struct AnotherView : View {
var body: some View {
Text("Second View")
.bold()
.font(.largeTitle)
}
}
ZStack
内使用Rectangle
来为模态视图提供背景。但是...模态视图的默认设置似乎基于浅色/深色模式设置。如果您使该矩形填充为Color.clear
,则仍将有一个覆盖底层视图的背景... - user7014451