在WWDC 2019上,Apple宣布了一种新的“卡式”外观模态演示,并带有内置手势,可通过向下滑动卡来消除模态视图控制器。他们还引入了新isModalInPresentation属性,UIViewController以便您可以选择拒绝这种解雇行为。
isModalInPresentation
UIViewController
但是到目前为止,我还没有找到在SwiftUI中模拟这种行为的方法。使用.presentation(_ modal: Modal?),不,据我所知,让你以同样的方式禁止解雇手势。我还尝试将模式视图控制器放在内UIViewControllerRepresentable View,但这似乎也无济于事:
.presentation(_ modal: Modal?)
UIViewControllerRepresentable
View
struct MyViewControllerView: UIViewControllerRepresentable { func makeUIViewController(context: UIViewControllerRepresentableContext<MyViewControllerView>) -> UIHostingController<MyView> { return UIHostingController(rootView: MyView()) } func updateUIViewController(_ uiViewController: UIHostingController<MyView>, context: UIViewControllerRepresentableContext<MyViewControllerView>) { uiViewController.isModalInPresentation = true } }
即使出现了,.presentation(Modal(MyViewControllerView()))我仍然可以向下滑动以消除视图。当前是否可以使用现有的SwiftUI构造来做到这一点?
.presentation(Modal(MyViewControllerView()))
通过更改gesture priority您不想拖动的DragGesture任何视图的,可以防止出现在任何视图上。例如对于Modal,可以按以下方式完成:
gesture priority
DragGesture
也许这不是最佳做法,但是效果很好
struct ContentView: View { @State var showModal = true var body: some View { Button(action: { self.showModal.toggle() }) { Text("Show Modal") }.sheet(isPresented: self.$showModal) { ModalView() } } }
struct ModalView : View { @Environment(\.presentationMode) var presentationMode let dg = DragGesture() var body: some View { ZStack { Rectangle() .fill(Color.white) .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) .highPriorityGesture(dg) Button("Dismiss Modal") { self.presentationMode.wrappedValue.dismiss() } } } }