At first I created a UIViewRepresentable to wrap a UITextField... and that works... There is, however, another option which takes advantage of the fact that it seems the SwiftUI TextField is actually already implemented as a UITextField. By observing the UITextField.textDidBeginEditingNotification I managed to change the keyboard.
This is an ugly, ugly hack... that works. I leave it hear mostly for purely academic purposes... I don't think I would like to use this on production code:
import SwiftUI
let dirtyWork = DirtyWork()
struct ContentView : View {
@State private var emailAccount: String = ""
@State private var twitterAccount: String = ""
var body: some View {
return VStack {
TextField($emailAccount, onEditingChanged: { if $0 { dirtyWork.keyboardType = .emailAddress } }).textFieldStyle(.roundedBorder)
TextField($twitterAccount, onEditingChanged: { if $0 { dirtyWork.keyboardType = .twitter } }).textFieldStyle(.roundedBorder)
Spacer()
}
}
}
class DirtyWork {
var keyboardType: UIKeyboardType = .twitter // some default
init() {
NotificationCenter.default.addObserver(self, selector: #selector(didBegin(notification:)), name: UITextField.textDidBeginEditingNotification, object: nil)
}
@objc func didBegin(notification: Notification) {
if let tf = notification.object as? UITextField {
tf.keyboardType = keyboardType
}
}
}