当诸如日期选择器之类的另一个控件变为活动状态时,是否有一种简单的方法可以消除键盘或任何其他活动控件?反之亦然。
有一些解散键盘的解决方案,但也会禁用选择器。
除了onTapGesture之外,可能还有其他事件要使用。
以下是一些说明问题的示例代码。
struct TestView: View {
@State private var firstname = ""
@State private var surname = ""
@State private var birthdate = Date()
@State private var activeField: Int = 0
var body: some View {
Form {
Section{
TextField("Firstname", text: self.$firstname)
TextField("Surname", text: self.$surname)
TextField("Surname", text: self.$surname, onEditingChanged: { (editingChanged) in
if editingChanged {
print("TextField focused")
} else {
print("TextField focus removed")
self.endEditing()
}
})
}
Section(header: Text("Time: ")){
DatePicker(selection: self.$birthdate, in: ...Date(), displayedComponents: .date) {
Text("Date of Birth")
}
.onTapGesture {
self.endEditing()
}
DatePicker(selection: self.$birthdate, in: ...Date(), displayedComponents: .hourAndMinute) {
Text("Date of Birth")
}
}
}
}
func endEditing() {
//UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
keyWindow?.endEditing(true)
}
}
答案 0 :(得分:0)
除了onTapGesture
之外,您还可以添加onAppear
。这样可以解决您的担忧
DatePicker(selection: self.$birthdate, in: ...Date(), displayedComponents: .date) {
Text("Date of Birth")
}
.onAppear{self.endEditing()}
.onTapGesture{self.endEditing()}