Hey there,
I have a problem with a search bar inside the navigation controller, because it doesn't get focus by code like it should. I want to achieve similar behavior, like the search bar in the calendar app has. I have a search icon in the navigation bar. If pressed, I segue to a new view controller and add a search bar to the navigation bar through code. Then I animate the nav bar in and the search text field should get focus automatically, so that the keyboard opens and everything. But this does not happen. If I click the field manually, the keyboard appears, but there is no blinking cursor inside the text field. Here is the code I use to create the search controller and bar. Last two lines seem not to do anything. I have already double checked, that searchController is not nil.
class WOSSearchViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UITableViewDataSource, UITableViewDelegate {
var searchController: UISearchController? = nil
var searchResults: [WOSSearchResult] = []
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
searchController?.searchResultsUpdater = self
searchController?.delegate = self
searchController?.searchBar.delegate = self
searchController?.dimsBackgroundDuringPresentation = false
searchController?.hidesNavigationBarDuringPresentation = false
searchController?.searchBar.showsCancelButton = true
searchController?.searchBar.sizeToFit()
navigationItem.titleView = searchController?.searchBar
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
UIView.animateWithDuration(0.2, animations: {() -> Void in
self.view.layer.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).CGColor
})
searchController?.searchBar.becomeFirstResponder() // does not work
searchController?.searchBar.window?.makeKeyAndVisible() // does not work
}
}Thanks for any help.