Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Make autoLayout for UISearchController when rotate the device?

I'm using a UISearchController integrate with my tableview. For making my searchBar not scrolling with the table, I already made a View (name SearchBarView) under the navigation bar and my table is under this view. All element on my view is setting up using auto layout: enter image description here

In my code. I make a UISearchController like a subview of SearchBarView and using sideToFit function for auto fit the width of the screen like this:

      self.resultSeachController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()

//            add searchbar in the searchbarView
            self.searchBarView.addSubview(controller.searchBar)
            return controller
        })()

My SearchBar is working perfect now except one: when I rotate the simulator, the searchBar is not automatic fit the width of screen. It only fit the screen when I touch the SearchBar for searching something. enter image description hereenter image description hereenter image description hereenter image description here

I don't know how to fix. I tried this code :

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

        self.resultSeachController.searchBar.sizeToFit()

    }

But It's still not working. How can I fix that?

like image 690
Hieu Duc Pham Avatar asked Sep 28 '22 00:09

Hieu Duc Pham


1 Answers

Do it while animating along with the transition:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [_searchController.searchBar sizeToFit];
    } completion:nil];
}
like image 195
Cedrick Avatar answered Nov 15 '22 06:11

Cedrick