首先通過(guò)擴(kuò)展 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)")
}) {
//當(dāng)用戶點(diǎn)擊返回按鈕時(shí)調(diào)用
print("onEditing:\(self.cityName)")
}
.padding([.top, .leading, .trailing], 20.0)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("城市名稱:\(cityName)")
Spacer()
}
.background(Color.white) //測(cè)試時(shí)發(fā)現(xiàn)必須設(shè)置,不然點(diǎn)擊空白處無(wú)效 (有點(diǎn)懵逼)
.onTapGesture {
print("測(cè)試點(diǎn)擊")
UIApplication.shared.endEditing()
}
}