5

How to dismiss Keyboard in SwiftUI

 9 months ago
source link: https://sarunw.com/posts/dismiss-keyboard-in-swiftui/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to dismiss Keyboard in SwiftUI

Learn how to programmatically dismiss a keyboard in SwiftUI.


In iOS 15, SwiftUI got a native way to dismiss the keyboard programmatically using a new property wrapper, @FocusState, in conjunction with focused(_:) modifier.

How to dismiss Keyboard programmatically in SwiftUI

Keyboard show and hide based on the focus state of a text field.

  • When a text field gain focus, the keyboard will show.
  • When a text field loss focus, the keyboard will disappear.

To dismiss the keyboard, we need to be able to control the focus of the text field.

You can easily support sarunw.com by checking out this sponsor.

AI Paraphrase:

Sponsor sarunw.com and reach thousands of iOS developers.

How to control the focus state.

We can listen and control the focus state on a particular input using focused(_:) modifier.

This modifier needs a special type called FocusState to bind the focus state.

Here is an example where we hide the keyboard when the "Sign In" button is tapped.

struct ContentView: View {
@State private var username = ""
// 1
@FocusState private var isFocused: Bool

var body: some View {
VStack {
// 2
TextField("Username", text: $username)
.focused($isFocused)
Button("Sign In") {
// 3
isFocused = false
}
}
.padding()
}
}

1 We create a @FocusState variable to bind with the focus state of the text field.
2 We bind the focus state using .focused($isFocused) modifier.
3 To dismiss the keyboard, we unfocus the text field by setting the focus state to false, isFocused = false.

When we tapped the text field:

  1. It will gain focus.
  2. isFocused will become true.
  3. And the keyboard will show.

When we set isFocused back to false:

  1. The text field gives up its focus.
  2. And the keyboard will dismiss.
Programmatically dismiss the keyboard using isFocused.

Programmatically dismiss the keyboard using isFocused.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK