how do I dismiss keyboard when a UIView receives accessibilityElementDidLoseFocus

131 Views Asked by At

I have a search view controller with the search bar on top. When searching, the keyboard shows up and stay up even when accessibilityElementDidLoseFocus is called on the search bar.

I would like to dismiss the keyboard when that happens. Can I do that without subclassing the search bar I am using?

2

There are 2 best solutions below

0
Pincha On BEST ANSWER

Here is a way to do that without subclassing:

// Assuming you have an accessibility element with an identifier
let myAccessibilityElement = UIAccessibilityElement(accessibilityContainer: self)

// Observe accessibility focus changes
NotificationCenter.default.addObserver(
    self, 
    selector: #selector(accessibilityElementDidLoseFocus), 
    name: UIAccessibilityElement.didLoseFocusNotification, 
    object: myAccessibilityElement
)

@objc func accessibilityElementDidLoseFocus() {
    // Dismiss keyboard here
}
0
Vishal K On

To dismiss the keyboard when a UIView loses focus without subclassing the search bar, you can implement the UISearchBarDelegate (or UITextFieldDelegate) and use the searchBarCancelButtonClicked (or a similar method for text fields) to call resignFirstResponder() on the active search bar or text field.

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        searchBar.delegate = self
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
}