Black Friday 2024 deal: 30% off our Swift and SwiftUI books! Learn more ...Black Friday 2024 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

Hide and show a view with opacity

Sometimes we need to hide and show a view in SwiftUI depending on a setting or state, but don’t want our layout to shift when the view appears.

We can use opacity() modifier to make the view fully opaque or transparent.

struct ContentView: View {
    @State var showMessage = false
    
    var body: some View {
        VStack {
            Button("Toggle message") {
                showMessage.toggle()
            }
            Text("Welcome!")
                .opacity(showMessage ? 1 : 0)
        }
    }
}

Fully transparent views are also hidden from VoiceOver.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Black Friday 2024 offer: 30% off!$35$25

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
Black Friday 2024 offer: 30% off!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35$25