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)
相关推荐
denggun1234512 分钟前
内存优化-(二)-oc&swift
ios·性能优化·cocoa·内存·swift
我要用代码向我喜欢的女孩表白1 小时前
对象存储路径文件1TB以上文件比对,go语言
ios·golang·xcode
2501_916007472 小时前
iPhone APP 性能测试怎么做,除了Instruments还有什么工具?
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 小时前
Windows 环境下有哪些可用的 iOS 上架工具, iOS 上架工具的使用方式
android·ios·小程序·https·uni-app·iphone·webview
Student_Zhang4 小时前
一个管理项目中所有弹窗的弹窗管理器(PopupManager)
前端·ios·github
denggun123454 小时前
使用 os_unfair_lock 替代 DispatchQueue?!
ios
2501_915106326 小时前
iOS 抓包工具有哪些?不同类型的抓包工具可以做什么
android·ios·小程序·https·uni-app·iphone·webview
一点晖光9 小时前
ios底部按钮被挡住
前端·ios·微信小程序
chinesegf19 小时前
iTunes Lookup API 规则具体(查包名)
ios
C+++Python1 天前
iOS 长截图
ios