Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss keyboard in SwiftUI Keyboard when pressing done?

In SwiftUI, TextField("", text: $input) has this automatic behavior, when you press done, the keyboard is dismissed. This is exactly what I wanted with the done button.

However, if you use TextField("", text: $input, axis: .vertical) the done button will become line change instead, and will no longer dismiss the keyboard.

I need scrollable TextField as TextField("", text: $input, axis: .vertical). At the same time, pressing done button to dismiss the keyboard instead of line change. Does anyone knows how to achieve it? Thank you!

enter image description here

like image 733
Legolas Wang Avatar asked Sep 17 '25 13:09

Legolas Wang


1 Answers

I think you have to add one button above the keyboard which is called Tool bar button

Hope this will help

struct ContentView: View {
private enum Field: Int, CaseIterable {
    case username
}

@State private var username: String = ""

@FocusState private var focusedField: Field?

var body: some View {
    NavigationView {
            TextField("Username", text: $username)
                .focused($focusedField, equals: .username)
        .toolbar {
            ToolbarItem(placement: .keyboard) {
                Button("Done") {
                    focusedField = nil
                }
            }
        }
    }
}}
like image 109
Hetali Bhimjiyani Avatar answered Sep 19 '25 05:09

Hetali Bhimjiyani