首先通过扩展 UIApplication
extension UIApplication{
func endEditing(){
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
然后在需要的地方添加 UIApplication.shared.endEditing()
var body: some View {
VStack {
TextField("城市名称", text: $cityName, onEditingChanged: { (value) in
print("onEditingChanged:\(self.cityName)")
}) {
//当用户点击返回按钮时调用
print("onEditing:\(self.cityName)")
}
.padding([.top, .leading, .trailing], 20.0)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("城市名称:\(cityName)")
Spacer()
}
.background(Color.white) //测试时发现必须设置,不然点击空白处无效 (有点懵逼)
.onTapGesture {
print("测试点击")
UIApplication.shared.endEditing()
}
}