SwiftUI
iOS development
keyboard management
app design
Swift programming

How to hide keyboard when using SwiftUI?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

In SwiftUI, the best way to hide the keyboard depends on the iOS version and the shape of the screen. On modern iOS, @FocusState is the preferred approach because the keyboard follows view state cleanly. For older compatibility or UIKit interop, you can still dismiss the current responder manually, but that should usually be the fallback rather than the default design.

The Preferred Modern Approach: @FocusState

On iOS 15 and later, clear the focus to dismiss the keyboard.

swift
1import SwiftUI
2
3struct LoginView: View {
4    enum Field: Hashable {
5        case email
6        case password
7    }
8
9    @State private var email = ""
10    @State private var password = ""
11    @FocusState private var focusedField: Field?
12
13    var body: some View {
14        Form {
15            TextField("Email", text: $email)
16                .focused($focusedField, equals: .email)
17
18            SecureField("Password", text: $password)
19                .focused($focusedField, equals: .password)
20
21            Button("Sign In") {
22                focusedField = nil
23                submit()
24            }
25        }
26    }
27
28    private func submit() {
29        print("submit")
30    }
31}

Setting focusedField = nil removes focus and hides the keyboard.

Dismiss on Background Tap

Many apps also dismiss the keyboard when the user taps outside the field.

swift
1import SwiftUI
2
3struct TapDismissView: View {
4    @State private var text = ""
5    @FocusState private var isFocused: Bool
6
7    var body: some View {
8        VStack(spacing: 16) {
9            TextField("Type here", text: $text)
10                .textFieldStyle(.roundedBorder)
11                .focused($isFocused)
12
13            Text("Tap empty area to dismiss")
14        }
15        .padding()
16        .contentShape(Rectangle())
17        .onTapGesture {
18            isFocused = false
19        }
20    }
21}

The contentShape(Rectangle()) call helps the tap gesture cover empty layout space too.

A Toolbar Button Helps on Number Pads

Numeric keyboards often have no return key, so a toolbar button is a good dismissal affordance.

swift
1TextField("Amount", text: .constant(""))
2    .keyboardType(.decimalPad)
3    .toolbar {
4        ToolbarItemGroup(placement: .keyboard) {
5            Spacer()
6            Button("Done") {
7                UIApplication.shared.sendAction(
8                    #selector(UIResponder.resignFirstResponder),
9                    to: nil,
10                    from: nil,
11                    for: nil
12                )
13            }
14        }
15    }

This improves usability even if the rest of the screen does not use focus-state-based dismissal.

UIKit Fallback for Older or Mixed Setups

If the app mixes SwiftUI with UIKit or supports older patterns, responder-chain dismissal still works.

swift
1import SwiftUI
2import UIKit
3
4extension View {
5    func hideKeyboard() {
6        UIApplication.shared.sendAction(
7            #selector(UIResponder.resignFirstResponder),
8            to: nil,
9            from: nil,
10            for: nil
11        )
12    }
13}

Then call it from a button or gesture.

swift
Button("Done") {
    hideKeyboard()
}

This is practical, but it is less explicit than focus management.

Think About Layout and Navigation Too

Keyboard dismissal is not just about hiding the keyboard. It is also about keeping forms usable during focus changes, navigation, and screen-size changes.

Good practices include:

  • testing on small devices
  • checking portrait and landscape behavior
  • clearing focus on submit or route transitions when appropriate
  • making sure tap gestures do not interfere with controls

A keyboard that technically dismisses but causes layout flicker or blocked taps is still a UX problem.

Common Pitfalls

  • Using UIKit responder tricks everywhere instead of adopting @FocusState on modern SwiftUI screens.
  • Forgetting to clear focus after submit actions.
  • Adding a broad tap gesture that interferes with buttons or list interactions.
  • Providing no dismissal path for decimal or number-pad keyboards.
  • Testing only one screen size and missing overlap or scroll issues on smaller devices.

Summary

  • '@FocusState is the preferred SwiftUI keyboard-control mechanism on modern iOS.'
  • Clearing focus dismisses the keyboard cleanly.
  • Background taps and keyboard toolbars improve usability for form-heavy screens.
  • UIKit responder-chain dismissal is still useful as a fallback.
  • Good keyboard behavior includes layout, focus, and navigation polish, not only the hide action itself.

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.