SwiftUI
iOS Development
View Management
Dynamic UI
Swift Programming

Dynamically hiding view in SwiftUI

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

SwiftUI gives you several ways to hide a view, and they are not interchangeable. Some approaches remove the view from the hierarchy, while others keep its layout space and only change what the user sees. Picking the right strategy makes the difference between a stable interface and a screen that jumps, misreads accessibility state, or leaves invisible tap targets behind.

First Decide Whether Layout Should Collapse

The most important question is not "how do I hide this view," but "what should happen to the surrounding layout when the view disappears." If the hidden content should vanish completely and let nearby views move, conditional rendering is usually the cleanest choice.

swift
1struct ProfileCard: View {
2    @State private var showDetails = false
3
4    var body: some View {
5        VStack(spacing: 16) {
6            Toggle("Show details", isOn: $showDetails)
7
8            if showDetails {
9                Text("Premium account enabled")
10                    .padding()
11                    .background(Color.blue.opacity(0.1))
12                    .cornerRadius(8)
13            }
14        }
15        .padding()
16    }
17}

When showDetails is false, the detail view is not part of the hierarchy at all. That usually matches user expectations for sections that expand and collapse.

Preserve Layout When Stability Matters

Sometimes removing the view is the wrong experience. Validation messages, loading indicators, and status labels often look better when the surrounding layout stays fixed. In that case, keep the view in place and change its visual state instead.

swift
1Text("Invalid email address")
2    .opacity(showError ? 1 : 0)
3    .accessibilityHidden(!showError)
4    .allowsHitTesting(showError)

This keeps the reserved space even while the text is visually hidden. That prevents nearby controls from shifting every time the error state changes.

The accessibilityHidden and allowsHitTesting calls matter. Without them, a hidden view may still confuse VoiceOver or intercept taps.

Use a Modifier for Consistent Behavior

Once a team uses preserved-layout hiding in more than one place, it is worth extracting a modifier. That keeps the logic readable and reduces inconsistent copies.

swift
1import SwiftUI
2
3struct HiddenPreservingLayout: ViewModifier {
4    let hidden: Bool
5
6    func body(content: Content) -> some View {
7        content
8            .opacity(hidden ? 0 : 1)
9            .accessibilityHidden(hidden)
10            .allowsHitTesting(!hidden)
11    }
12}
13
14extension View {
15    func hiddenPreservingLayout(_ hidden: Bool) -> some View {
16        modifier(HiddenPreservingLayout(hidden: hidden))
17    }
18}

With that in place, form code stays simple:

swift
Text("Required field")
    .foregroundColor(.red)
    .hiddenPreservingLayout(!showError)

This is more maintainable than repeating three modifiers every time a view needs to hide without collapsing.

Animate the Chosen Strategy Deliberately

Animations should match the hiding technique. If you are conditionally inserting and removing a view, transitions are the right tool. If you are fading a view that stays in the layout, animate opacity instead.

swift
1if showDetails {
2    Text("Expanded section")
3        .transition(.move(edge: .top).combined(with: .opacity))
4}
5
6Button("Toggle") {
7    withAnimation(.easeInOut(duration: 0.25)) {
8        showDetails.toggle()
9    }
10}

Without a deliberate animation choice, a view may seem to jump or flash rather than hide gracefully.

Drive Visibility From Clear State

Visibility bugs often come from scattered booleans that stop making sense once the screen grows. A better pattern is to derive view visibility from a small amount of authoritative state.

swift
1struct LoginState {
2    var isLoading: Bool
3    var errorMessage: String?
4
5    var showSpinner: Bool { isLoading }
6    var showError: Bool { errorMessage != nil }
7}

This makes it easier to reason about what should be visible at any moment and reduces contradictory states such as showing both success and error content together.

Test Interaction and Accessibility, Not Just Appearance

A hidden view can still be interactive if hit testing is left enabled, and a visually gone view can still be announced by assistive technologies if accessibility state is not updated. That is why testing should include taps, VoiceOver behavior, and dynamic-type layouts, not just screenshots.

If the screen hides content frequently, it is also worth checking older devices. Expensive views that are repeatedly inserted and removed may behave differently from lighter content. Performance should be measured on the actual screen, not guessed from the API name.

Common Pitfalls

The biggest mistake is choosing a hiding technique without first deciding whether layout should collapse. Another is hiding a view visually while forgetting to disable hit testing or accessibility exposure. Teams also get into trouble with too many independent flags, which makes visibility logic impossible to trust or review.

Summary

  • Choose hiding behavior based on whether layout space should remain.
  • Use conditional rendering when the view should be removed entirely.
  • Use opacity-based hiding when layout stability matters.
  • Keep accessibility and hit-testing aligned with the visual state.
  • Extract a modifier when the same hiding pattern appears across multiple views.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.