Reputation: 699
Can't find any example of using SwiftUI in Keyboard Extension.
I create an extension and trying to create simple SwiftUI
Button
with no action (it just prints debug text). But there is no visible button in Keyboard.
Is it possible to create SwiftUI custom keyboard?
struct SwiftUIButton: View{
let action: () -> ()
var body: some View{
Button(action: action){Text("Tap me")}
}
}
class KeyboardViewController: UIInputViewController {
@IBOutlet var nextKeyboardButton: UIButton!
//1.insert this: SwiftUIButton is a simple Button View
var swiftUIButtonView: SwiftUIButton!
//...
override func viewDidLoad() {
super.viewDidLoad()
// Perform custom UI setup here
//2. try to insert my SwiftUI View
let swiftUIButtonView = SwiftUIButton(action: {print("test")})
let vc = UIHostingController(rootView: swiftUIButtonView)
//I tried that with no success
//guard let inputView = inputView else { return }
//inputView.addSubview(vc.view)
self.view.addSubview(vc.view)
//all that following code is standard from Xcode
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
self.view.addSubview(self.nextKeyboardButton)
self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
When I try to test it in simulator, I see empty Keyboard
and some errors in debug console:
2020-01-23 02:07:13.421876+0300 SwiftUIKeyboard[4723:376225] Failed to inherit CoreMedia permissions from 4717: (null) 2020-01-23
02:07:13.460713+0300 SwiftUIKeyboard[4723:375598] [External] -[UIInputViewController needsInputModeSwitchKey] was called before a connection was established to the host application. This will produce an inaccurate result. Please make sure to call this after your primary view controller has been initialized.
last message repeats 6 times.
What am I doing wrong? Or do I need to create UIKit Keyboard View and implement SwiftUI inside of it?
Upvotes: 4
Views: 3085
Reputation: 699
oh it was rough to deal with UIKit, but I made it.
// Perform custom UI setup here
let child = UIHostingController(rootView: SwiftUIButton())
//that's wrong, it must be true to make flexible constraints work
// child.translatesAutoresizingMaskIntoConstraints = false
child.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(child.view)
addChild(child)//not sure what is this for, it works without it.
works fine. Even GeometryReader inside of SwiftUI View gets bounds well.
Upvotes: 6