Visual Effects in SwiftUI

swiftui May 24, 2022
Visual Effects in SwiftUI

Swift provides with different ways of displaying visual effects like blur and vibrancy effects. These can mostly be used as background for views and can be used to improve the overall app design. You can observe these blur effects throughout iOS like in app library, control center and app dock.

Materials

Adding visual effect as background in iOS 15 is as easy as doing the following:

 Text("Hello, World!")
            .frame(width: 200, height: 50)
            .background(.thickMaterial)

Result:



Note:

If you are using any frame in your view, use the .background after that so that the background effect is applied for the required frame size.

This visual effect is actually an enum called Material which has thin, thick and regular properties.


Source: Developer Apple

Visual Effect using UIViewRepresentable

Above was the case for iOS 15+ only. But for >iOS15, you can use a mini UIViewRepresentable to implement visual effect into your app.

struct VisualEffect: UIViewRepresentable {
    @State var style : UIBlurEffect.Style // 1
    func makeUIView(context: Context) -> UIVisualEffectView {
        return UIVisualEffectView(effect: UIBlurEffect(style: style)) // 2
    }
    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
    } // 3 
}

Code Explanation:

  1. Defining the state variable to take in the blur effect enum as a parameter.
  2. Returning a UIVisualEffectView (UIKit element) with the style variable.
  3. Since no view updates are required, no code is added to updateUIView.

Usage:

  Text("Hello, World!”)
            .frame(width: 150, height: 50, alignment: .center)
            .background(VisualEffect(style: .systemThickMaterial))

Result: 

 

There can be cases where on adding the blur effect to the view, the visual effect can look no different than a solid background color. In that case, you just need to play around with the alpha and opacity value of the visual effect.

Text("Hello, World!")
    .frame(width: 150, height: 50, alignment: .center)
    .background(.thin)
    .background(
        VisualEffect(style: .systemThickMaterial)
            .opacity(0.8)
    )

If you are looking forward to implement vibrancy effects like before, SwiftUI doesn't support the vibrancy effect natively. For that, you could go for Swift Packages like SwiftUI Visual Effects by Lucas Brown.

Wrapping up the article, today you learned about implementatoin of visuals effects in SwiftUI by using Material and about integrating the UIKit version. We encourage you to go over the concept of Colors & gradient in SwiftUI .

Signup now to get notified about our
FREE iOS Workshops!