Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Adjust View Opacity in SwiftUI
Written by Team Kodeco

Adjusting the opacity of a view can be useful in creating different visual effects for your app interface. For example, you can create a translucent overlay to show a notification, or you can fade elements in and out with animation. With SwiftUI, adjusting view opacity is very easy and can be done by using the opacity modifier.

Here’s an example of how to adjust the opacity of a view:

struct ContentView: View {
  var body: some View {
    VStack {
      Text("This text has full opacity.")
      Text("This text is partially transparent.")
        .opacity(0.5)
    }
  }
}

The preview for this view should look as follows:

An example of using the opacity modifier in SwiftUI.
An example of using the opacity modifier in SwiftUI.

In this code, we have created a VStack with two Text views. The first Text view has full opacity by default, while the second Text view has an opacity of 0.5, which means it will appear partially transparent. The opacity value can range from 0 (fully transparent) to 1 (fully opaque).

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.