使用自定义按钮扩展SwiftUI键盘 [英] Extend SwiftUI Keyboard with Custom Button

查看:365
本文介绍了使用自定义按钮扩展SwiftUI键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种将键或按钮添加到SwiftUI数字键盘的方法.唯一的 我发现的参考资料说这是不可能的.在Swift世界中,我添加了一个工具栏 并带有一个按钮以关闭键盘或执行某些其他功能.

I'm trying to find a way to add a key or button to the SwiftUI numberPad. The only references I have found say it is not possible. In the Swift world I added a toolbar with a button to dismiss the keyboard or perform some other function.

我什至会用顶部的按钮构建一个ZStack视图,但是我找不到添加该视图的方法. numberPad转到我自己的视图.

I would even build a ZStack view with the button on top but I can't find a way to add the numberPad to my own view.

在这种情况下,我真正想做的就是在数据为 输入.我首先尝试修改SceneDelegate以在点击时关闭,但是 仅当我在另一个文本或文本字段视图中而不是在该视图的开放空间中点击时才有效.

All I'm really trying to do in this case is dismiss the numberPad when the data is entered. I first attempted to modify the SceneDelegate to dismiss on taps, but that only works if I tap in another text or textfield view not in open space on the view.

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

理想情况下,我将完成"键添加到左下角.其次最好添加一个工具栏,如果 可以在SwiftUI中完成.

Ideally, I'd add a Done key to the lower left space. Second best add a toolbar if it can be done in SwiftUI.

任何指导将不胜感激.

Xcode版本11.2.1(11B500)

Xcode Version 11.2.1 (11B500)

推荐答案

使用UIRepresentable协议解决了该问题

Solved the issue using UIRepresentable protocol

 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)
    )
}

}

这篇关于使用自定义按钮扩展SwiftUI键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆