gpt4 book ai didi

SwiftUI 从 UITextField 中关闭键盘

转载 作者:行者123 更新时间:2023-12-04 07:32:33 29 4
gpt4 key购买 nike

因此,出于我自己的原因,我需要 UITextField 及其委托(delegate)通常提供的完全控制,但它添加到的屏幕是用 SwiftUI 编写的。需要 .decimal 键盘,因此不需要 Return 键。

我只剩下 2 个问题,其中 1 个我希望在这里解决。尝试添加一个调用来退出第一响应者并将其添加到页面上的 VStack 基本上会禁用 UITextField,因为我无法调出键盘。

如何在不向页面添加任意额外按钮的情况下关闭此键盘?

示例代码:

Struct CustomTextView: UIViewRepresentable {
/// Insert init, updateView, binding variable, coordinator, etc
func makeView() -> UITextField {
var textField = UITextField()
textField.delegate = context.coordinator
/// Set up rest of textfield parameters such as Font, etc.
return textField
}
}

extension CustomTextView {
class Coordinator: NSObject, UITextFieldDelegate {
/// UITextfield delegate implementations, extra reference to binding variable, etc
/// Primarily textField.shouldChangeCharactersInRange
}
}

struct ContentView: View {
@State viewModel: ViewModel
var body: some View {
VStack {
CustomTextView($viewModel.parameter)
/// Other views
}
.onTap {
/// Attempting to add the generic call to UIApplication for resignFirstResponder here does not allow CustomTextView to ever hold it even when tapped in
}
}
}

出于隐私原因,我无法提供所有代码,但这应该足以确定我的问题。

最佳答案

我通过将此函数添加到下面的 View 中来完成此操作。

    func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}

然后使用 ontapGesture 就可以让键盘消失。例如,您可以在整个 View 的背景堆栈上使用它。如果用户点击背景,键盘就会消失。

.onTapGesture {
self.hideKeyboard()
}

关于SwiftUI 从 UITextField 中关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67877405/

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