首页 > 解决方案 > SwiftUI 旋转屏幕使模态不再自行消失

问题描述

我在 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 14.2 beta 和 Xcode 12 GM [1] 上使用 iOS 13:https ://twitter.com/MisaelLandero/status/1306953785651142656?s=20

标签: iosswiftswiftui

解决方案


尝试使用这样的东西:

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")
      }
    }
  }
}

推荐阅读