【问题标题】:SwiftUI Rotate screen make modal don’t longer dismiss itselfSwiftUI 旋转屏幕使模态不再自行消失
【发布时间】:2021-09-22 23:11:11
【问题描述】:

我在 SwiftUI 上有一个错误,当我旋转我的设备时,模态不再消失,这里的问题是只发生在模拟器上的设备上,我的 iPad 上也能正常工作。

import SwiftUI

struct modalView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button(action:{
            self.presentationMode.wrappedValue.dismiss()
        }){
            Text("close")
        }
    }
}

struct ContentView: View {
    @State var showModal = false
    var body: some View {
        Button(action: {
            showModal.toggle()
        }){
            Text("modal")
        }
        .sheet(isPresented: self.$showModal, content: {
            modalView()
        })
    }
}

[我设备上的错误][1]

我从 iOS 13 开始就有这个问题 我目前在 iOS 14.2 beta 和 Xcode 12 通用 [1]:https://twitter.com/MisaelLandero/status/1306953785651142656?s=20

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    尝试使用这样的东西:

    struct ContentView: View {
    
      @State private var showModal = false
    
      // If you are getting the "can only present once" issue, add this here.
      // Fixes the problem, but not sure why; feel free to edit/explain below.
      @Environment(\.presentationMode) var presentationMode
    
    
      var body: some View {
        Button(action: {
            self.showModal = true
        }) {
            Text("Show modal")
        }.sheet(isPresented: self.$showModal) {
            ModalView()
        }
      }
    }
    
    
    struct ModalView: View {
    
      @Environment(\.presentationMode) private var presentationMode
    
      var body: some View {
        Group {
          Text("Modal view")
          Button(action: {
             self.presentationMode.wrappedValue.dismiss()
          }) {
            Text("Dismiss")
          }
        }
      }
    }
    

    【讨论】:

    • 嘿,谢谢,但我有同样的错误,只是在 iPad 上的 iPhone btw 上工作正常。
    【解决方案2】:

    我发现了问题,我使用一个条件来显示两个不同的导航视图,这打破了解除模式

    if self.sizeClass == .compact{
    NavigationViewForiPhone()
    } else {
    NavigationViewForiPad()
    } 
    

    看起来这就是问题,因为我的视图正在重新加载

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多