paescebu / CustomKeyboardKit

Creating custom In App Keyboards with SwiftUI has never been easier!
GNU General Public License v3.0
201 stars 20 forks source link

Question: Can this be used when creating a custom keyboard extension? #21

Closed puhgeh closed 5 months ago

puhgeh commented 6 months ago

Is it possible to incorporate this in a custom keyboard extension?

If so, would you be able to provide an example on how to use it inside the KeyboardViewController: UIInputViewController?

Thanks!

paescebu commented 6 months ago

@puhgeh let me look into this further. If you want to use SwiftUI in your KeyboardViewController class, you can simply just add a SubView which embeds the UIHostingController with the SwiftUI View of your choice. This library is not needed for that, especially as it has to fullfill some other requirements to work well with other Keyboards from iOS (e.g. Keyboard switching etc.). You probably won't need this Swift package :)

But to simply embed a SwiftUI View into your KeyboardViewController you should be able to do something along those lines (code not checked if it compiles):

public class KeyboardViewController: UIInputViewController {
    var keyboardView: UIViewController!

    public init() {
        super.init(nibName: nil, bundle: nil)
        keyboardView = UIHostingController(rootView: yourSwiftUIKeyboard)
        addChild(keyboardView)
        view.addSubview(keyboardView.view)
        setupContraints()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @ViewBuilder
    var yourSwiftUIKeyboard: some View {
         Button("A") {
               self.textDocumentProxy.insertText("A")
         }
         Button("B") {
               self.textDocumentProxy.insertText("B")
         }
    }

    private func setupContraints() {
        keyboardView.view.translatesAutoresizingMaskIntoConstraints = false
        keyboardView.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        keyboardView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        keyboardView.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        keyboardView.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }
}