在编辑后隐藏键盘,UISearchbar隐藏自己?

问题描述 投票:-2回答:2

我使用导航控制器呈现了一个屏幕,在该屏幕中我有一个搜索栏,我在viewWillAppear()中作为第一响应者。问题是我想在单击完成按钮或单击searchBar中取消时隐藏键盘。但是在对resignFirstResponder()和searchBar.endEditing(true)做同样的事情时,它也隐藏了UISearchBar。我想在状态不在编辑时显示UISearchBar。

基本上我所做的就是让我的UISearchBar成为我的第一个响应者:

override func viewWillAppear(_ animated: Bool) {
    searchBar.becomeFirstResponder()
}

然后当用户点击搜索时我做了:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    // Remove focus from the search bar.
}

取消按钮的情况也是如此。但在我的情况下,而不是只是解雇键盘,这也调用上述函数后隐藏UISearchbar()。

ios swift uisearchbar first-responder resignfirstresponder
2个回答
0
投票

使用NotificationCenter addObserver获取键盘显示和键盘的事件隐藏

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// MARK: - Keyboard Hide/Show Functions
@objc func keyboardWillShowNotification(notification: Notification) {
    print("Keyboaed Show")
}

@objc func keyboardWillHideNotification(notification: Notification) {
    print("Keyboaed Hide")
}

注意: - 当UIviewContoller消失时,不要忘记移除观察者。

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

0
投票

在这种情况下使用NotificationCenter是更好的方法。你不共享任何代码,所以我将在我的旧项目中给出一个例子

在ViewDidLoad函数中声明这一点

override func viewDidLoad() {
    super.viewDidLoad()

     NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

并在Button动作中创建一个函数

@objc func keyboardHide() {

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
        self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) 
    }, completion: nil)

}

上面的代码应该隐藏键盘超过0.5秒。

© www.soinside.com 2019 - 2024. All rights reserved.