提问者:小点点

使用自定义按钮扩展SwiftUI键盘


我正在想办法给SwiftUI数字板添加一个键或按钮。 我找到的唯一参考资料都说这是不可能的。 在Swift世界中,我添加了一个带有按钮的工具栏,用于关闭键盘或执行其他功能。

我甚至会构建一个顶部有按钮的ZStack视图,但我找不到将数字板添加到我自己的视图中的方法。

在这种情况下,我真正要做的就是在输入数据时取消数字板。 我首先尝试将SceneDelegate修改为在点击时关闭,但只有当我在另一个text或textfield视图中点击而不是在视图的开放空间中时,这才起作用。

window.rootViewController = UIHostingController(rootView: contentView.onTapGesture {
    window.endEditing(true)
})

理想情况下,我会在左下方的空白处添加一个Done键。 其次,如果可以在SwiftUI中完成,最好添加一个工具栏。

如有任何指导,将不胜感激。

Xcode版本11.2.1(11B500)


共1个答案

匿名用户

使用UIRepresentable协议解决了这个问题

 struct TestTextfield: UIViewRepresentable {
    @Binding var text: String
    var keyType: UIKeyboardType
    func makeUIView(context: Context) -> UITextField {
        let textfield = UITextField()
      textfield.keyboardType = keyType
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
        let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))
        toolBar.items = [doneButton]
        toolBar.setItems([doneButton], animated: true)
        textfield.inputAccessoryView = toolBar
        return textfield
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text

    }
}

extension  UITextField{
    @objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
       self.resignFirstResponder()
    }

}

在内容视图中使用

struct ContentView : View {
@State var text = ""

var body: some View {
    TestTextfield(text: $text, keyType: UIKeyboardType.phonePad)
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 50)
        .overlay(
            RoundedRectangle(cornerRadius: 16)
                .stroke(Color.blue, lineWidth: 4)
    )
}

}