Reputation: 71
I am new to swiftUI.I need to create a keyboard extension in swiftui. I just can't find out how to do that. I am searching on internet for whole day but still can't find out how to do that. Here is some code that I wrote :
struct ContentView: View {
var body: some View {
VStack{
keyboard()
}
}
}
struct keyboard: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIInputViewController {
let inputVC = UIInputViewController()
return inputVC
}
func updateUIViewController(_ uiViewController: UIInputViewController, context: Context) {
print("some text")
}
}
The above code is written in extension folder's keyboardViewController.swift file and not giving me any kind of keyboard display.
IF I write UIKit UIInputController (the file created itself when we create an extension) code in same file then only I can see a keyboard extension appearing.
I want to design keyboard in UIKit Inputviewcontroller type of class and then display it using UIViewControllerRepresentable in swiftui contentview.
Now my question is-> Is this Approach right?? IF yes then please guide me ahead. IF no then please suggest me the right approach.
Thanks in advance!!
Upvotes: 6
Views: 2679
Reputation: 311
Here's my approach using UIHostingController
:
When I added a new target "Keyboard" of keyboard extension, XCode automatically generated a class KeyboardViewController
:
class KeyboardViewController: UIInputViewController {
// some code
override func viewDidLoad() {
super.viewDidLoad()
self.nextKeyboardButton = UIButton(type: .system)
// some code
}
// some code
}
I added the view through UIHostingController
with my keyboard view as the rootView
of it. Then added it and its view as children of KeyboardViewController
and the view of KeyboardViewController
:
class KeyboardViewController: UIInputViewController {
// some code
override func viewDidLoad() {
super.viewDidLoad()
let hostingController = UIHostingController(rootView: KeyboardView(viewController: self))
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(hostingController.view)
addChild(hostingController)
self.nextKeyboardButton = UIButton(type: .system)
// some code
}
// some code
}
And my KeyboardView
was like:
struct KeyboardView: View {
var viewController: KeyboardViewController
var body: some View {
// some view as you designed
}
}
It worked for me.
Upvotes: 8