複数モーダル(sheetやフルスクリーンなど)を開いている場合、一気に一番初めの階層に戻りたい時
以下二つのどっちか実行するだけで戻れる。
UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true)
または
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
window?.rootViewController?.dismiss(animated: true)
Example
struct ContentView: View {
@State var isPresented = false
var body: some View {
Button(action: {
isPresented.toggle()
}) {
Text("ContentView")
.font(.title3)
.background(.gray)
.padding()
}
.fullScreenCover(isPresented: $isPresented) {
Sample2View()
}
}
}
struct Sample1View: View {
@State var isPresented = false
var body: some View {
Button(action: {
isPresented.toggle()
}) {
Text("Sample1View")
.font(.title3)
.background(.black)
.padding()
}
.fullScreenCover(isPresented: $isPresented) {
Sample2View()
}
}
}
struct Sample2View: View {
@State var isPresented = false
var body: some View {
Button(action: {
isPresented.toggle()
}) {
Text("Sample2View")
.foregroundColor(.white)
.font(.title3)
.background(.green)
.padding()
}
.fullScreenCover(isPresented: $isPresented) {
Sample3View()
}
}
}
struct Sample3View: View {
@State var isPresented = false
var body: some View {
Button(action: {
isPresented.toggle()
}) {
Text("Sample3View")
.foregroundColor(.white)
.font(.title3)
.background(.blue)
.padding()
}
.fullScreenCover(isPresented: $isPresented) {
Sample4View()
}
}
}
struct Sample4View: View {
var body: some View {
Button(action: {
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
window?.rootViewController?.dismiss(animated: true)
}) {
Text("Sample4View")
.foregroundColor(.white)
.font(.title3)
.background(.red)
.padding()
}
}
}
以下やと、iOS15でなんたらこんたらって警告でた。
UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true)