oivvio
oivvio

Reputation: 3156

Semi-transparent (blurry like VisualEffectView) of the view behind the current view

In SwiftUI the view behind the tab bar in a TabView will shine through as if the backside of the tab bar was frosted glass. Apple uses this look all over the place in their own apps. But how do I add it to a view in SwiftUI?

Here's an example from the Podcasts app. The tab bar has the frosted glass effect. And so does the overlay mini player on top of the tab bar. Any tab bar in a TabView in will have this look by default, but not an associated overlay (the mini player in this case).

enter image description here

Upvotes: 31

Views: 19905

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119878

The Apple way

Investigating on the view hierarchy shows that Apple is using UIKit and UIVisualEffectViewfor this reason. You can define a VisualEffectView with just 5 lines of code:

struct VisualEffectView: UIViewRepresentable {
    var effect: UIVisualEffect?
    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView { UIVisualEffectView() }
    func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) { uiView.effect = effect }
}

Usage Example:

struct ContentView: View {

    var body: some View {
        ZStack {
            Image("BG")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)
            
            VisualEffectView(effect: UIBlurEffect(style: .dark))
                .edgesIgnoringSafeArea(.all)
                
            Text("Hello \nVisual Effect View")
                .font(.largeTitle)
                .fontWeight(.black)
                .foregroundColor(.white)
        }
    }
}

Visual Effect View


The Native SwiftUI way:

You can add .blur() modifier on anything you need to be blurry like:

struct ContentView: View {

    var body: some View {
        ZStack {
            Image("BG")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)
                .blur(radius: 20) // <- this is the important modifier. The rest is just for demo
                
            Text("Hello \nSwiftUI Blur Effect")
                .font(.largeTitle)
                .fontWeight(.black)
                .foregroundColor(.white)
        }
    }
}

SwiftUI Code Note the top and bottom of the view

Note that you can Group multiple views and blur them together.


iOS 15 - Apple Material

You can use iOS predefined materials with one line code:

.background(.ultraThinMaterial)

Demo

Upvotes: 77

Related Questions