【问题描述】
在SwiftUI中使用TextView,当输入完成后,想要继续往下操作时,键盘却无法智能地收缩起来,给下面的操作留下空间。
【解决方案】
- 增加一个扩展方法
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
- 在需要隐藏的地方调用这个方法
func dispareKeyboard(){
UIApplication.shared.endEditing()
}
- 如果希望点击键盘中的回车,触发隐藏键盘的动作
TextField("Title", text: $title){
self.dispareKeyboard()
}
- 如果希望点击某个地方触发键盘隐藏的动作
TextView(text: $content)
.onTapGesture {
self.dispareKeyboard()
}