是否可以在内联导航栏上叠加某些内容?这是一个带有弹出窗口的示例,您可以在其中显示并发出警报,然后点击警报外部以关闭它。
我希望深色背景覆盖也覆盖导航栏。这适用于默认的大文本样式导航栏,但是当我将其更改为内联导航栏时,深色背景不再覆盖导航。有解决方法吗?
import SwiftUI
struct ContentView: View {
@State private var isPresented = false
var body: some View {
NavigationView {
ZStack {
Button(action: {
isPresented = true
}) {
Text("Show popup")
}
if isPresented {
ZStack {
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
.edgesIgnoringSafeArea(.all)
.onTapGesture {
isPresented = false
}
Rectangle()
.foregroundColor(Color.red)
.frame(width: 300, height: 100)
.onTapGesture {
isPresented = true
}
Text("Alert!")
}
}
}
.navigationBarTitle("Hello", displayMode: .inline)
}
}
}
答案 0 :(得分:1)
将 NavigationView 包裹在 ZStack 中。
struct ContentView: View {
@State private var isPresented = false
var body: some View {
ZStack { // < -- Here
NavigationView {
ZStack {
Button(action: {
isPresented = true
}) {
Text("Show popup")
}
}
.navigationBarTitle("Hello", displayMode: .inline)
}
if isPresented {
ZStack {
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
.edgesIgnoringSafeArea(.all)
.onTapGesture {
isPresented = false
}
Rectangle()
.foregroundColor(Color.red)
.frame(width: 300, height: 100)
.onTapGesture {
isPresented = true
}
Text("Alert!")
}
}
}
}
}
另一种使用叠加层的方法。
struct ContentView: View {
@State private var isPresented = false
var body: some View {
NavigationView {
ZStack {
Button(action: {
isPresented = true
}) {
Text("Show popup")
}
}
.navigationBarTitle("Hello", displayMode: .inline)
}.overlay( //<--- Here
alertView
)
}
@ViewBuilder
private var alertView: some View {
if isPresented {
ZStack {
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
.edgesIgnoringSafeArea(.all)
.onTapGesture {
isPresented = false
}
Rectangle()
.foregroundColor(Color.red)
.frame(width: 300, height: 100)
.onTapGesture {
isPresented = true
}
Text("Alert!")
}
}
}
}