Skip to content

Instantly share code, notes, and snippets.

@rnystrom
Created January 18, 2021 00:30
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnystrom/32affa160288574f9ff9b3205f2d145b to your computer and use it in GitHub Desktop.
Save rnystrom/32affa160288574f9ff9b3205f2d145b to your computer and use it in GitHub Desktop.
Show the keyboard as a UISearchController in a modal is displayed
class ViewController: UIViewController {
@IBAction func onSearch(_ sender: Any) {
let fakeWindow = UIWindow(windowScene: view.window!.windowScene!)
let fakeTextField = UITextField()
fakeTextField.autocorrectionType = .no
fakeWindow.addSubview(fakeTextField)
fakeWindow.makeKeyAndVisible()
fakeTextField.becomeFirstResponder()
present(SearchModalViewController(), animated: true) {
fakeWindow.resignKey()
fakeWindow.removeFromSuperview()
}
}
}
class SearchModalViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate {
private let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
searchController.obscuresBackgroundDuringPresentation = false
searchController.delegate = self
tableView.tableHeaderView = searchController.searchBar
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchController.isActive = true
}
func willPresentSearchController(_ searchController: UISearchController) {
DispatchQueue.main.async {
searchController.searchBar.becomeFirstResponder()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment