[英]SwiftUI navigation bar appearance and functionality when custom popup shows
我正在嘗試顯示一個自定義彈出窗口,當它顯示時,我需要禁用背景並將其變暗,就像在內置警報功能中所做的那樣。 但是,當視圖中有導航欄時,彩色圖層不能放在導航欄的頂部。
期望的結果就像在內置警報修改器中所做的那樣,使整個背景變暗(使用導航欄),同時禁用與背景(和導航欄)交互的能力。
有沒有辦法實現與內置警報修改器相同的功能和外觀?
示例項目代碼
import SwiftUI
struct ContentView: View {
@State private var isShowingPopup = false
var body: some View {
NavigationView {
VStack {
Text("Just a random text")
.padding(.bottom, 100)
Button("Show popup") {
isShowingPopup = true
}
}
.showPopup(isActive: isShowingPopup, action: { isShowingPopup = false })
.navigationBarTitle("Test navbar", displayMode: .inline)
.navigationBarItems(
trailing: Button(
action: { print("profile tapped")},
label: {
Text("Profile")
}
)
)
}
}
}
extension View {
func showPopup(
isActive: Bool,
action: @escaping () -> Void
) -> some View {
ZStack {
self
if isActive {
Color.black
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
.opacity(0.51)
.zIndex(1)
Popup(action: action)
.zIndex(2)
}
}
}
}
struct Popup: View {
let action: () -> Void
var body: some View {
VStack {
Text("This is a popup")
.foregroundColor(.black)
.padding()
Button("OK", action: action)
.foregroundColor(.blue)
}
.background(Color.white)
.cornerRadius(8)
}
}
謝謝你的幫助!
最后加入。 在 NavigationView 的最后添加showPopup
NavigationView {
VStack {
Text("Just a random text")
.padding(.bottom, 100)
Button("Show popup") {
isShowingPopup = true
}
}
.navigationBarTitle("Test navbar", displayMode: .inline)
.navigationBarItems(
trailing: Button(
action: { print("profile tapped")},
label: {
Text("Profile")
}
)
)
}
.showPopup(isActive: isShowingPopup, action: { isShowingPopup = false }) //<---Here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.