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

SwiftUI in target (custom keyboard)

找不到任何在键盘扩展中使用 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
    }

当我尝试在模拟器中对其进行测试时,我看到空的键盘

调试控制台中出现一些错误:

2020-01-23 02:07:13.421876+0300 SwiftUIKeyboard[4723:376225] Failed to inherit CoreMedia permissions from 4717: (null) 2020-01-23

02:07:13.460713+0300 SwiftUIKeyboard[4723:375598] [External] -[UIInputViewController needsInputModeSwitchKey] was called before a connection was established to the host application. This will produce an inaccurate result. Please make sure to call this after your primary view controller has been initialized.

最后一条消息重复 6 次。

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

哦,处理 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.

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