gpt4 book ai didi

ios - Swift 5 NumberPad 扩展按钮无响应

转载 作者:行者123 更新时间:2023-12-01 21:45:15 26 4
gpt4 key购买 nike

我在数字键盘上有一个完成按钮,当我输入一个值并按下完成时,该值没有保存/注册。我的代码如下:

我正在使用 UIRepresentable 协议(protocol)(由 Rajeev Kumar S 提供)

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

}

我在我的内容 View 中得到了这个
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)
)
}

This is the numberpad

这就是我正在使用的:
  • swift 5
  • Xcode 11.5

  • Xcode 11.5

    最佳答案

    您只需要将您的可代表类更新为此!

    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
    textfield.delegate = context.coordinator
    return textfield
    }

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

    uiView.text = text
    }

    func makeCoordinator() -> Coordinator {
    Coordinator($text)
    }

    class Coordinator: NSObject, UITextFieldDelegate {

    @Binding var text: String

    init(_ text: Binding<String>) {
    self._text = text
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? ""

    return true
    }
    }
    }

    尝试一下!

    关于ios - Swift 5 NumberPad 扩展按钮无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62300723/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com