【问题标题】:In Swiftui How to automatically close modal with rotation to landscape在 Swiftui 中如何通过旋转到横向自动关闭模态
【发布时间】:2020-07-08 18:30:05
【问题描述】:
我目前使用基于此代码的景观环境对象 - https://stackoverflow.com/a/58503841/412154
在我看来,我的模态使用@State/@Binding 适当地出现和消失,具体取决于“完成”按钮的按下。我的应用在旋转到横向时确实显示了不同的视图,我希望模式在旋转时自动关闭,但无法弄清楚如何根据另一个 @ennvironmentobject 更改 @binding var
这是我的模态视图的简化示例
struct StepsView: View {
@Binding var isPresented:Bool
@EnvironmentObject var orientation:Orientation
var body: some View {
VStack(alignment: .center) {
Text("Step")
}
.navigationBarItems(trailing: Button(action: {
//print("Dismissing steps view...")
self.isPresented = false
}) {
Text("Done").bold()
})
}
感谢您的帮助!
【问题讨论】:
标签:
ios
swift
xcode
swiftui
【解决方案1】:
感谢@davidev 的回答,但我希望每个模态的行为都有点不同,所以我这样做了
struct StepsView: View {
@Binding var isPresented:Bool
@EnvironmentObject var orientation:Orientation
private var PortraitView:some View {
VStack(alignment: .center) {
Text("Modal")
}
.navigationBarItems(trailing: Button(action: {
self.isPresented = false
}) {
Text("Done").bold()
})
}
var body: some View {
buildView(isLandscape: orientation.isLandScape, isShowing: &isPresented)
}
func buildView(isLandscape:Bool, isShowing:inout Bool) -> AnyView {
if !isLandscape {
return AnyView(PortraitView)
} else {
isShowing = false
return AnyView(EmptyView())
}
}
【解决方案2】:
这是一种可能的方法,使用一个变量来扩展 Device 类,该变量跟踪打开的模态视图。
import Combine
final class Orientation: ObservableObject {
@Published var isLandscape: Bool = false {
willSet {
objectWillChange.send()
if (newValue)
{
self.showModal = false
}
}
}
@Published var showModal : Bool = false
}
每当横向改变,并且方向是横向时,showModal 将被设置为 false。
这里是 ContentView..
struct ContentView6: View {
@EnvironmentObject var orientation:Orientation
// 1.
@State private var showModal = false
var body: some View {
Button("Show Modal") {
// 2.
self.orientation.isLandscape.toggle()
// 3.
}.sheet(isPresented: self.$orientation.isLandscape) {
ModalView(isPresented: self.$orientation.isLandscape).environmentObject(self.orientation)
}
}
}