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.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit