我正在使用 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
我也无法打印它,但按钮肯定可以工作。您只需将一个函数传递给视图并在按钮的操作部分中调用它:
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)
}