Reputation: 17685
Aim: To have a search bar that is always visible.
UISearchController
What I have done:
Problem:
Expected behavior:
Question
Code:
func setupSearchController() {
searchController.searchResultsUpdater = self
self.definesPresentationContext = false
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = true
let searchBar = searchController.searchBar
view.addSubview(searchBar)
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
searchBar.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
searchBar.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor).active = true
}
func presentSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
searchBar.removeFromSuperview()
let baseView = searchController.view
baseView.addSubview(searchBar)
searchBar.leadingAnchor.constraintEqualToAnchor(baseView.leadingAnchor).active = true
searchBar.trailingAnchor.constraintEqualToAnchor(baseView.trailingAnchor).active = true
searchBar.topAnchor.constraintEqualToAnchor(searchController.topLayoutGuide.bottomAnchor).active = true
self.presentViewController(searchController, animated: true) {
}
}
Upvotes: 7
Views: 3727
Reputation: 14780
I am not quite following your logic there, but all I can say is that you can implement this really easy.
UIView
will be the container
of the searchController
's searchBar
and set the constraints as
following:UIView
to the UIViewController
and name it searchBarContainerUISearchController
that you want to use: var searchController: UISearchController! = nil
Luckily your controller should look like this: (Note that here I have not implemented the delegates here but you can take care of that as this is not related to the animation :))
class SearchViewController: UIViewController {
var searchController: UISearchController! = nil
@IBOutlet weak var searchBarContainer: UIView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
self.searchBarContainer.addSubview(searchController.searchBar)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Setup the frame each time that the view appears in order to fit the width of the screen
// If you use autolayout just call searchController.searchBar.layoutIfNeeded()
var frame = searchController.searchBar.bounds
frame.size.width = self.view.bounds.size.width
searchController.searchBar.frame = frame
}
}
My Solution
iOS Contacts
Upvotes: 8