Created
January 18, 2021 00:30
-
-
Save rnystrom/32affa160288574f9ff9b3205f2d145b to your computer and use it in GitHub Desktop.
Show the keyboard as a UISearchController in a modal is displayed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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