如何在swiftui中创建键盘应用扩展程序?

时间:2020-09-22 07:10:32

标签: swiftui

我是swiftUI的新手。我需要在swiftui中创建一个键盘扩展。我只是不知道该怎么做。我整天都在互联网上搜索,但仍然找不到该怎么做的方法。 这是我写的一些代码:

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")
    }
     
} 

上面的代码写在扩展文件夹的keyboardViewController.swift文件中,没有给我任何形式的键盘显示。

如果我在同一文件中编写UIKit UIInputController(在创建扩展名时创建的文件)代码,那么只有我可以看到键盘扩展名出现。

我想设计UIKit Inputviewcontroller类类的键盘,然后在swiftui contentview中使用UIViewControllerRepresentable显示它。

现在我的问题是->这种方法正确吗?如果是,那么请指导我。如果没有,请提出正确的方法。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

这是我使用UIHostingController的方法:

当我添加键盘扩展的新目标“ Keyboard”时,XCode自动生成一个类KeyboardViewController

class KeyboardViewController: UIInputViewController {
    // some code
    override func viewDidLoad() {
        super.viewDidLoad()
        self.nextKeyboardButton = UIButton(type: .system)
        // some code
    }
    // some code
}

我通过UIHostingController添加了视图,其中键盘视图为视图的rootView。然后将其及其视图作为KeyboardViewController的子级和KeyboardViewController的视图添加:

class KeyboardViewController: UIInputViewController {
    // some code
    override func viewDidLoad() {
        super.viewDidLoad()
        let hostingController = UIHostingController(rootView: KeyboardView(viewController: self))
        view.addSubview(hostingController.view)
        addChild(hostingController)

        self.nextKeyboardButton = UIButton(type: .system)
        // some code
    }
    // some code
}

我的KeyboardView就像:

struct KeyboardView: View {
    var viewController: KeyboardViewController
    var body: some View {
        // some view as you designed
    }
}

对我有用。