UISearchBar in UINavigationBar changes width when

2019-07-24 14:08发布

This is driving me crazy. I am creating a splitview app on iPad.

I have created a searchBar inside the UINavigationBar - something like this...

UISearchBar *searchBar = [[UISearchBar alloc] initWitFrame:CGRectZero];
[searchBar setPlaceHolder:@"Search"];
[searchBar sizeToFit];
[searchBar setDelegate:self];
[self.navigatioItem setTitleView:searchBar];

this works just fine for me displaying the UISearchBar like this...

enter image description here

I also have this UIBarButtonItem set to show Master navigation controller in sidepane.

The problem happens when the device rotates to landscape and the UIBarButtonItem gets hidden. Then the searchBar appears like this...

enter image description here

there is some space on sides which appears to be there since the barButtonItem got hidden and the size of search bar couldn't be updated.

Furthermore, when I rotate the device again, here's what happens to UISearchBar

enter image description here

How can I update the size of searchbar once it has been added to UINavigationBar. Even using autoResizingMask does not work.

searchBar.autoResizingMask =UIViewAutoresizingFlexibleWidth;

What am I doing wrong over here?

1条回答
beautiful°
2楼-- · 2019-07-24 15:07

I had about the same problem (it wasn't searchbar, but some UIView), and that's how I solved it:

Try creating it with fixed size that won't change. I mean if your navbar minimum size is (for example) 320pt, and barbutton is about 30pt, and you need searchbar to be placed right in the middle (which, BTW is not standart, AFAIK), you'd have to make it 320 - (30+10)*2 = 240pt. Searchbar would be placed right in the middle and will have enough place left free.

This way it will neither change it's size, nor it will affect other items.

Or I would suggest you placing it at right position, not in the middle.

Hope it helped.

查看更多
登录 后发表回答