【问题标题】:SwiftUI navigation bar appearance and functionality when custom popup shows自定义弹出窗口显示时的 SwiftUI 导航栏外观和功能
【发布时间】:2021-04-29 03:52:46
【问题描述】:

我正在尝试显示一个自定义弹出窗口,当它显示时,我需要禁用背景并将其变暗,就像在内置警报功能中所做的那样。但是,当视图中有导航栏时,彩色图层不能放在导航栏的顶部。

所需的结果就像在内置警报修改器中所做的那样,使整个背景变暗(使用导航栏),同时禁用与背景(和导航栏)交互的能力。

有没有办法实现与内置警报修饰符相同的功能和外观?

示例项目代码

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

感谢您的帮助!

【问题讨论】:

    标签: ios swiftui popup navbar


    【解决方案1】:

    最后添加。在 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
    
    

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      相关资源
      最近更新 更多