我是 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 显示它。
现在我的问题是-> 这种方法正确吗??如果是,请指导我前进。如果否,请建议我正确的方法。
提前致谢!
最佳答案
这是我使用 UIHostingController
的方法:
当我添加键盘扩展的新目标“Keyboard”时,XCode 自动生成了一个类KeyboardViewController
:
class KeyboardViewController: UIInputViewController {
// some code
override func viewDidLoad() {
super.viewDidLoad()
self.nextKeyboardButton = UIButton(type: .system)
// some code
}
// some code
}
我通过 UIHostingController
添加了 View ,我的键盘 View 作为它的 rootView
。然后将它和它的 View 添加为 KeyboardViewController
的子级和 KeyboardViewController
的 View :
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
}
}
它对我有用。
关于swiftui - 如何在 swiftui 中创建键盘应用程序扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64004701/