Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change "return" key to "done" on keyboard with SwiftUI?

Tags:

swift

swiftui

I didn't find any link or guide to change the "return" key to "done" when keyboard open for TextField in SwiftUI.

Is it possible now without customising UITextField?

like image 756
Andro Developer Avatar asked Jan 31 '20 17:01

Andro Developer


4 Answers

iOS 15

You can change the return key for each textField with a simple modifier called: submitLabel that takes the return key type:

enter image description here Image from WWDC21

Also, as you can see, you can have a callback to handle the return key press action just like the old textFieldShouldReturn function that is accessible by .onSubmit modifier.

⚠️ Seems like there is a bug on Xcode 13 beta 1 that prevents this modifier from working in some situations.

like image 172
Mojtaba Hosseini Avatar answered Oct 03 '22 11:10

Mojtaba Hosseini


Update

This is no longer a good solution. In iOS 15 you can now add a .submitLabel(.done) modifier. Please see Mojtaba's answer for more details.


Old Answer

The best way I found was to just add the package Introspect to your project.

After doing so add in import Introspect anywhere in your project files.

Then add one of their View Modifiers to your Textfield to achieve what you want. I believe this is what you want though ⤵

.introspectTextField { textfield in
  textfield.returnKeyType = .done
}

What Does Introspect Do?

It exposes UIKit to be used in SwiftUI. So that Textfield object you see above there has access to all UITextfield functionality! This is a package though so be aware it could break in the future but for now this is a good option.

It's just nice because it saves you from making your own UIKit wrapper for every View 😊

like image 40
tyirvine Avatar answered Oct 03 '22 10:10

tyirvine


iOS 15.0+

macOS 12.0+, Mac Catalyst 15.0+, tvOS 15.0+, watchOS 8.0+

submitLabel(_:)

Sets the submit label for this view.

https://developer.apple.com

Form {
    TextField("Username", $viewModel.username)
        .submitLabel(.done)
}
like image 24
mahan Avatar answered Oct 03 '22 09:10

mahan


To get the go button on the keyboard. Try changing the keyboardtype to .webSearch.

// Tested on Xcode 12 beta 2 and iOS 14

.keyboardType(.webSearch)

like image 22
karmjit singh Avatar answered Oct 03 '22 10:10

karmjit singh