Skip to main content

How to adjust the opacity of a view

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to adjust the opacity of a view 관련

SwiftUI by Example

Back to Home

How to adjust the opacity of a view | SwiftUI by Example

How to adjust the opacity of a view

Updated for Xcode 15

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

For example, this creates a text view with a red background, then gives it 30% opacity:

Text("Now you see me")
    .padding()
    .background(.red)
    .opacity(0.3)

Download this as an Xcode projectopen in new window

The text “Now you see me” in a red rectangle. Both are translucent.
The text “Now you see me” in a red rectangle. Both are translucent.

Modifying opacity is extremely fast – certainly something you can do as often as you need. To demonstrate that, the following code adjusts text opacity using a slider, and you’ll see you can move it around as fast and as much as you like without any performance hit:

struct ContentView: View {
    @State private var opacity = 0.5

    var body: some View {
        VStack {
            Text("Now you see me")
                .padding()
                .background(.red)
                .opacity(opacity)

            Slider(value: $opacity, in: 0...1)
                .padding()
        }
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to dynamically adjust the appearance of a view based on its size and location | SwiftUI by Example

How to dynamically adjust the appearance of a view based on its size and location
How to adjust the position of a view using its offset | SwiftUI by Example

How to adjust the position of a view using its offset
How to adjust the size of a view relative to its container | SwiftUI by Example

How to adjust the size of a view relative to its container
How to adjust the accent color of a view | SwiftUI by Example

How to adjust the accent color of a view

이찬희 (MarkiiimarK)
Never Stop Learning.