SwiftUI 添加全局点击隐藏键盘

需求场景:

当用户输入完毕,通过点击空白处,快捷实现键盘收起;同时也不影响其他正常的交互操作。

在UIKit中隐藏键盘的方法

  1. textField.resignFirstResponder()
  2. view.endEditing(true)

本质上是需要获取到承载键盘的视图

SwiftUI添加方法

SwiftUI 没有之前 View 的概念了,但是同样可以获取到整个 App 的 window,从而调用 endEditing。

给 UIApplication 增加 Extension

复制代码
// MARK: - 全局点击隐藏键盘分类
extension UIApplication {
    
    public func addTapHideKeyBoardGesture() {
        guard let window = windows.first else { return }
        
        let tapGesture = UITapGestureRecognizer(target: window, action: #selector(UIView.endEditing))
        tapGesture.requiresExclusiveTouchType = false
        tapGesture.cancelsTouchesInView = false
        tapGesture.delegate = self
        window.addGestureRecognizer(tapGesture)
    }
}

extension UIApplication: UIGestureRecognizerDelegate {
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true // 可以同时响应多个手势
    }
}

requiresExclusiveTouchType:默认为 true。这个属性是指是否允许多种手势输入,这里的多种包含触摸、遥控器、触控笔等,所以可以配置成 false
cancelsTouchesInView:默认为 true。这里设置为 false,主要为了不影响其他手势的识别。当前的 tap 手势被识别出来之后,也不会触发 UITouch 的 cancel 方法,因此就不会中断 UITouch 的传递。

最后加上手势识别

复制代码
.onAppear(perform: UIApplication.shared.addTapHideKeyBoardGesture)
相关推荐
2501_915106326 分钟前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
熊猫钓鱼>_>28 分钟前
移动端开发技术选型报告:三足鼎立时代的开发者指南(2026年2月)
android·人工智能·ios·app·鸿蒙·cpu·移动端
徐同保20 小时前
通过ip访问nginx的服务时,被第一个server重定向了,通过设置default_server解决这个问题
ios·iphone
2501_915918411 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
夏幻灵2 天前
HTTPS全面解析:原理、加密机制与证书体
ios·iphone
TheNextByte12 天前
如何在iPhone上恢复已删除的笔记的综合指南
笔记·ios·iphone
rose and war2 天前
python和jinja版本问题导致的访问报500
python·ios
fendoudexiaoniao_ios2 天前
iOS 列表拖拽cell排序
ios·swift
2501_915106322 天前
当 Perfdog 开始收费之后,我重新整理了一替代方案
android·ios·小程序·https·uni-app·iphone·webview