在用户使用SwiftUI在TextField
外部单击后,如何关闭键盘?
我使用SwiftUI创建了TextField
,但是如果用户在TextField
之外单击,我找不到解散键盘的任何解决方案。我查看了TextField
的所有属性以及SwiftUI TextField documentation的所有属性,但找不到与关闭键盘有关的任何内容。
这是我视图的代码:
struct InputView: View {
@State var inputValue : String = ""
var body: some View {
VStack(spacing: 10) {
TextField("$", text: $inputValue)
.keyboardType(.decimalPad)
}
}
}
答案 0 :(得分:6)
这可以通过视图修饰符完成。
public extension View {
func dismissKeyboardOnTap() -> some View {
modifier(DismissKeyboardOnTap())
}
}
public struct DismissKeyboardOnTap: ViewModifier {
public func body(content: Content) -> some View {
#if os(macOS)
return content
#else
return content.gesture(tapGesture)
#endif
}
private var tapGesture: some Gesture {
TapGesture().onEnded(endEditing)
}
private func endEditing() {
UIApplication.shared.connectedScenes
.filter {$0.activationState == .foregroundActive}
.map {$0 as? UIWindowScene}
.compactMap({$0})
.first?.windows
.filter {$0.isKeyWindow}
.first?.endEditing(true)
}
}
backgroundView()
.dismissKeyboardOnTap()
答案 1 :(得分:2)
这是使用DragGesture的解决方案。
struct ContentView: View {
@State var text: String = ""
var body: some View {
VStack {
TextField("My Text", text: $text)
.keyboardType(.decimalPad)
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
.gesture(
TapGesture()
.onEnded { _ in
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
)
}
}
答案 2 :(得分:0)
TextField("Phone Number", text: $no)
.keyboardType(.numbersAndPunctuation)
.padding()
.background(Color("4"))
.clipShape(RoundedRectangle(cornerRadius: 10))
.offset(y:-self.value).animation(.spring()).onAppear() {
NotificationCenter.default.addObserver(forName:UIResponder.keyboardWillShowNotification, object: nil, queue: .main){ (notif)in
let value = notif.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
let height = value.height
self.value = height
}
NotificationCenter.default.addObserver(forName:UIResponder.keyboardWillHideNotification, object: nil, queue: .main){ (notification)in
self.value = 0
}
}