我一直在到处找这个,但似乎找不到.我知道如何用Objective-C消除键盘,但我不知道如何用Swift消除键盘?有人知道吗?

推荐答案

override func viewDidLoad() {
    super.viewDidLoad()
          
    //Looks for single or multiple taps. 
     let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

    //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
    //tap.cancelsTouchesInView = false 

    view.addGestureRecognizer(tap)
}

//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

如果您要在多个UIViewControllers中使用此功能,以下是完成此任务的另一种方法:

// Put this piece of code anywhere you like
extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false            
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

现在每UIViewController个,你需要做的就是调用这个函数:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

此函数作为标准函数包含在我的repo中,其中包含许多有用的SWIFT扩展(如此),请查看它:https://github.com/goktugyil/EZSwiftExtensions

Ios相关问答推荐

将图案UI视图动画化以模拟进度条

自定义alert 未执行任何操作

如何调整包含extView的UICollectionViewListCell的大小?

在SWIFT中将圆角+透明背景从导入视频(.mp4)添加到导出视频(.mov)

XcodeCloud生成失败,返回";ci_pre_xcodeBuild.sh是可执行文件,但退出时返回2个退出代码.";

如果没有等待,SWIFT Async让任务抛出取消异常

安装新版本 XCode 15.0 后无法运行应用程序 XCode

使用 WebKit 加载 YouTube 视频时控制台中打印警告

SwiftUI:.toolbar 不适用于 UITextView

如何为 Firebase Auth 实施 Firebase AppCheck?

SKScene 的更新功能似乎不起作用

SwiftUI - ScrollView 不显示底部文本

在 iPad 上删除列表的顶部和底部行

使用 @MainActor 更新 UI 的适当策略是什么?

如何在 Swift 中从另一个视图控制器将元素附加到数组中

本月使用 iOS 的天数?

滑动列表项以获取更多选项(Flutter)

如何找出坐标之间的距离?

在代码生成的 UIView 上绘制 UIBezierPath

由于 NSInvalidUnarchiveOperationException 导致 iOS11 WKWebview 崩溃