gpt4 book ai didi

ios - 在搜索栏外单击时使键盘消失 - SWIFT

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:37 25 4
gpt4 key购买 nike

我有一个 UIViewController 并且嵌入了一个搜索栏和一个 Collection View 。当我按下搜索栏时,键盘出现。如果用户决定通过点击屏幕上除搜索栏以外的任何位置来改变主意,我想隐藏此键盘。我尝试了以下但没有成功:

  1. 添加点击手势识别器
  2. 使用“self.mySearchBar.endEditing(true)”

    class CollectionViewFolder: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout, UISearchBarDelegate{

    /*** OUTLETS ***/
    @IBOutlet weak var mySearchBar: UISearchBar!


    // 1. I have tried adding a Tap Gesture Recognizer
    // TAP ON SCREEN LISTENER
    @IBAction func tapOnScreen(_ sender: UITapGestureRecognizer) {
    print("tap tap ...")
    self.mySearchBar.resignFirstResponder()
    }



    // 2. Added the following to the viewDidLoad:
    override func viewDidLoad() {
    super.viewDidLoad()

    self.mySearchBar.endEditing(true)
    }

    }

enter image description here

最佳答案

您可以使用此扩展程序。

extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
view.endEditing(true)
}
}

用法。在你的 View Controller 中:

override func viewDidLoad() {
super.viewDidLoad()

hideKeyboardWhenTappedAround()
}

关于ios - 在搜索栏外单击时使键盘消失 - SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52019014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com