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

标签 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 显示它。

现在我的问题是-> 这种方法正确吗??如果是,请指导我前进。如果否,请建议我正确的方法。

提前致谢!

最佳答案

这是我使用 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/

相关文章:

ios - SwiftUI 模态演示仅在 navigationBarItems 中有效

SwiftUI 在按下按钮时添加音效

swiftui - SwiftUI 中的 GeometryReader 和 GeometryProxy 有什么区别?

ios - SwiftUI - 如何在纵向模式下删除使用 SidebarListStyle 样式的 List 后面的白色背景

ios - 关闭包含在 UIHostingController 中的 SwiftUI View

SwiftUI/UIKit 如何将 SwiftUI 字体转换为 UIKit UIFont?

ios - 在 SwiftUI 的列表行(TableviewCell)中单击按钮导航到详细 View

使用 Firebase pod 的 Xcode 12。词法或预处理器问题。 "pb.h' 文件未找到 <angled> 包含;使用 "quotes"代替”?

Xcode 预览恢复按钮快捷方式

swiftui - ObservableObject 中的 @Published 和普通 AnyPublisher 属性有什么区别