How to adjust the opacity of a view
About 2 min
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)
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()
}
}
}
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