Keyboard input for custom view in SwiftUI

I have a custom view in SwiftUI that I wish to accept and respond to keyboard input for. My current approach involves adding a TextField to manage the keyboard and responding to activity via onReceive(), which is functional. However, I really don’t want the TextField to be visible and I would like tapping on my custom view to display the keyboard (ie. set focus to the TextField). Any suggestions?

Hi @vincemarco, welcome to the forum community! What about trying to use the UIKeyInput protocol and implementing becomeFirstResponder with the view you have? I have not tried this myself but it is a suggestion that might be worth trying.

Hi @vincemarco,
I think you cannot make the textField the first responder easily. The way to achieve that would be to bridge to UIKit and use a native control.


If you want the keyboard to appear you have to make the TextField a responder (which it will do when the user taps into it). To do it programmatically you have to use its becomeFirstResponder message (function).

To do this in SwiftUI, you need to make a custom (UIViewRepresentable) for UITextField and have the Coordinator inside your customer control implement UITextFieldDelegate. Have your custom control accept a parameter like var isResponder: Bool and then in the custom control’s updateUI function, look at isResponder at sent the inner UITextField as the responder if isResponder is true. From the outside, or using your control:

@State var responderTag: Int = 0

MyInput(isResponder: self.responderTag == 1)

Then at some point, change responderTag to 1 and your control will get keyboard focus. Now having it move out of the way when the keyboard appears is a completely new topic.

This topic was automatically closed after 166 days. New replies are no longer allowed.