UIInputViewController 上未调用 SwiftUI 按钮

问题描述 投票:0回答:1

我正在使用 iOS 自定义键盘扩展。 SwiftUI 按钮显示正确,但从未被调用!

import SwiftUI

class KeyboardViewController: UIInputViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let vc = UIHostingController(rootView: MyKeyButtons())
        vc.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(vc.view)
    }
}


struct MyKeyButtons: View {

    let data: [String] = ["A", "B", "C"]
    var body: some View {
        HStack {
            ForEach(data, id: \.self) { aData in

                Button(action: {
                    print("button pressed!") // Not working!
                }) {
                    Text(aData).fontWeight(.bold).font(.title)
                        .foregroundColor(.white).padding()
                        .background(Color.purple)
                }
            }
        }
    }
}

为了更容易理解,以下是完整内容:https://github.com/ask2asim/KeyboardTest1

swift swift3 swiftui swift5
1个回答
0
投票

我也无法打印它,但按钮肯定可以工作。您只需将一个函数传递给视图并在按钮的操作部分中调用它:

let vc = UIHostingController(rootView: MyKeyButtons(btnPressed: { 
    self.dismissKeyboard() // dismiss keyboard action to test button press        
}

查看:

struct MyKeyButtons: View {

    let data: [String] = ["A", "B", "C"]
    let btnPressed: () -> Void
    
    var body: some View {
        HStack {
            ForEach(data, id: \.self) { aData in

                Button(action: {
                    btnPressed()
                }) {
                    Text(aData).fontWeight(.bold).font(.title)
                        .foregroundColor(.white).padding()
                        .background(Color.purple)
                }
            }
        }
    }
}

你显然也可以传递按下的字母:

let vc = UIHostingController(rootView: MyKeyButtons(keyPressed: { letter in
    self.textDocumentProxy.insertText(letter) // append letter to the end of the text input        
}

视图变化:

let keyPressed: (_ letter: String) -> Void


Button(action: {
          keyPressed(aData)
       }) {
          Text(aData).fontWeight(.bold).font(.title)
          .foregroundColor(.white).padding()
          .background(Color.blue)
       }
© www.soinside.com 2019 - 2024. All rights reserved.