目标中的 SwiftUI(自定义键盘)

Asp*_*pid 2 ios swift custom-keyboard swiftui

在键盘扩展中找不到任何使用 SwiftUI 的示例。我创建了一个扩展,并尝试创建简单的扩展,SwiftUI Button无需任何操作(它只是打印调试文本)。但键盘上没有可见的按钮。是否可以创建 SwiftUI 自定义键盘?

struct SwiftUIButton: View{
    let action: () -> ()
    var body: some View{
        Button(action: action){Text("Tap me")}
    }
}

class KeyboardViewController: UIInputViewController {
    
    @IBOutlet var nextKeyboardButton: UIButton!


//1.insert this: SwiftUIButton is a simple Button View
    var swiftUIButtonView: SwiftUIButton!
    //...
    override func viewDidLoad() {
        super.viewDidLoad()
        

        // Perform custom UI setup here

        //2. try to insert my SwiftUI View
        let swiftUIButtonView = SwiftUIButton(action: {print("test")})
        let vc = UIHostingController(rootView: swiftUIButtonView)
        //I tried that with no success
        //guard let inputView = inputView else { return }
        //inputView.addSubview(vc.view)
        self.view.addSubview(vc.view)

        //all that following code is standard from Xcode
        self.nextKeyboardButton = UIButton(type: .system)

        self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
        self.nextKeyboardButton.sizeToFit()
        self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false

        self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)

        self.view.addSubview(self.nextKeyboardButton)

        self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试在模拟器中测试它时,我看到空键盘

在此输入图像描述

以及调试控制台中的一些错误:

2020-01-23 02:07:13.421876+0300 SwiftUIKeyboard[4723:376225] 无法从 4717 继承 CoreMedia 权限: (null) 2020-01-23

02:07:13.460713+0300 SwiftUIKeyboard[4723:375598] [External] -[UIInputViewController needInputModeSwitchKey] 在与主机应用程序建立连接之前被调用。这会产生不准确的结果。请确保在初始化主视图控制器后调用此函数。

最后一条消息重复 6 次。

我究竟做错了什么?或者我是否需要创建 UIKit 键盘视图并在其中实现 SwiftUI?

Asp*_*pid 6

哦,处理 UIKit 很困难,但我做到了。

    // Perform custom UI setup here
    let child = UIHostingController(rootView: SwiftUIButton())
    //that's wrong, it must be true to make flexible constraints work
   // child.translatesAutoresizingMaskIntoConstraints = false
    child.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    view.addSubview(child.view)
    addChild(child)//not sure what is this for, it works without it.
Run Code Online (Sandbox Code Playgroud)

工作正常。甚至 SwiftUI View 中的 GeometryReader 也能很好地获得边界。