swiftswiftuiswiftui-tabviewswiftui-animationswiftui-view

Make second view gray SwiftUI


I have 2 views. 1 main view and 1 alert view. The alert view will appear in the front of the main view. I want to lower the white color from the entire main view when this happens. Like a gray or light gray when the alert view is on front.

My main view:

    struct MainView: View {
        @State private var showAlert = false


         var body: some View {

            VStack{ //multiple views
               
                  }//here I tried background, opacity, blur, but nothing works
                              
            
            if showAlert{
                   
                  AlertView(showAlert: $showAlert)              

            }

      }
    }

My alert view:

   struct AlertView View{
         let screenSize = UIScreen.main.bounds

         @Binding private var showAlert = false

         var body: some View {

            VStack{ //multiple views
        }
       .frame(width: screenSize.width * 0.85, height: screenSize.height * 0.7)
     
     }

  }

I tried using blur, background, opacity, but they still keep the color white. I want the entire background main view to change color, to be a bit gray when the alert view is open.


Solution

  • If you only need to change the greyscale value of the background view (no colored tints), use .brightness

    Example:

    struct MainView: View {
        @State private var showAlert = false
    
    
        var body: some View {
    
            VStack{
               // content
            }
            .brightness(showAlert ? -0.5 : 0)      //HERE
                                  
                
            if showAlert {
                  AlertView(showAlert: $showAlert)              
            }
       }
    }
    

    You could also try .overlay with a gray fill.

    P.S. using this in combination with a small blur usually looks really good