Search code examples
iosobjective-cuiviewuisearchcontroller

UISearchController searchBar frame only resizes on first click


I have just implemented a UISearchController in a regular UIViewController, and I have a kind of weird issue.

I have a UIView that is adapted exactly to the size I want my UISearchBar to take. On first launch of the view, I add my UISearchBar as a SubView to this UIView. But when I launch it, the UISearchBar doesn't take the size of its parent UIView -- it just takes the width of the whole screen.

enter image description here

As you can see, it overlaps with the button on the right.

But once I click on the search bar and cancel it, it resizes to the exact size I want.

enter image description here

What could be the issue here? I've tried adding AutoLayout Constraints from the SearchBar to its parent view but it doesn't seem to change anything. Doesn't [UIView addSubview:] handle this?


Solution

  • UISearchController's view behaviour is weird indeed, but there is a simple workaround.

    • Use an additional container view
    • put UISearchController's view inside
    • set UISearchController's view autoresizing mask to UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight
    • set UISearchController's frame to container's view bounds

    At this point UISearchController.view won't resize beyond container.bounds.