Ortwin Gentz
Ortwin Gentz

Reputation: 54121

How to animate alongside a UISearchController presentation/dismissal animation?

I have a table view with a search bar in the tableHeaderView, managed by a UISearchController. I use the standard UISearchController presentation animation.

I want to animate another view with the same duration as the searchBar animation. I tried various duration values but alas they don't match perfectly at all times.

So I thought it would be great to make use of the -[UIViewControllerTransitionCoordinator animateAlongsideTransition:completion:] API.

Unfortunately I can't find a reference of the <UIViewControllerTransitionCoordinator> object. Specifically, searchController.presentingViewController.transitionCoordinator is nil.

Upvotes: 12

Views: 2640

Answers (1)

juanjo
juanjo

Reputation: 3757

I had the same problem, I needed to animate other views alongside the the presentation of the UISearchController; After the call to present the search controller the transitionCoordinator becomes available and you can add code to animate your views

Presenting:

func search() {
    let searchController = UISearchController(searchResultsController: resultsController)
    // Configure search controller
    self.present(searchController, animated: true) {}

    self.transitionCoordinator?.animate(alongsideTransition: { (context) in
        // animate other views
    }, completion: nil)
}

I also had to animate the views while dismissing the search controller, in this case I implement the willDismissSearchController method of the UISearchControllerDelegate, the transitionCoordinator is not immediately available in this method but making an asynchronous call does the trick

Dismissing:

func willDismissSearchController(_ searchController: UISearchController) {
    DispatchQueue.main.async {
        searchController.transitionCoordinator?.animate(alongsideTransition: { (context) in
            // animate views
        }, completion: nil)
    }
}

This works for me from iOS 9

Upvotes: 7

Related Questions