Why is this UISearchBar getting resized?

纵饮孤独 提交于 2019-12-03 07:23:12

The difference is in the search bar's value of translatesAutoresizingMaskIntoConstraints. It defaults to NO for the XIB-based view and YES for the code-based view. Apparently, the search controller assumes a value of YES and doesn't set up any explicit constraints when it transplants the search bar.

Setting the value to YES in code should fix it (verified locally).

UPDATE

As noted in the comments, even with translatesAutoresizingMaskIntoConstraints = YES, the controller does not restore the header view to it's original state on cancel. But there does seem to be a workaround. You can create an outlet to your header view and restore it yourself in searchDisplayControllerDidEndSearch. I did a crude proof-of-concept (and updated my sample project):

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    self.tableView.tableHeaderView = self.headerView;
    [self.searchBar removeFromSuperview];
    self.searchBar.frame = CGRectMake(0, 20, 320, 44);
    [self.headerView addSubview:self.searchBar];
}

Following on from what both @TimothyMoose and @hpique have said about setting translatesAutoresizingMaskIntoConstraints = YES (yuck)

In my code I have found that if I do the following to show the searchDisplayController

self.searchDisplayController.searchBar.translatesAutoresizingMaskIntoConstraints = YES
[self.searchDisplayController setActive:YES animated:YES] 

and do the opposite when closing the searchDisplayController,

self.searchDisplayController.searchBar.translatesAutoresizingMaskIntoConstraints = NO
[self.searchDisplayController setActive:NO animated:YES] 

Then my view remains unchanged (everything goes back to what I'm expecting)

if i do not call the following line when closing

self.searchDisplayController.searchBar.translatesAutoresizingMaskIntoConstraints = NO

Then the view screws up.

The reason for this I believe is that the NSAutoresizingMaskLayoutConstraint are asserting them self and as they are the last in the constraint list, the Layout engine brakes the real constraint to satisfy the unwanted NSAutoresizingMaskLayoutConstraint constraints.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!