UISearchBar单击时修改其框架/边界

我试图在我的应用程序用户界面中放置一个UISearchController。 布局是:

  • 黄色:一个ViewController
  • 红色:另一个ViewController
  • 黑色:YellowViewController中的容器

在这里输入图像说明

我想把UISearchController的UISearchView放在黑色容器中。

我的代码如下:

self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsViewController]; UISearchBar* searchBar = self.searchController.searchBar; searchBar.frame =_searchBarContainer.bounds; [_searchBarContainer addSubview:searchBar]; [_searchBarContainer layoutIfNeeded]; 

它将UISearchBar放置在正确的位置:

在这里输入图像说明

但是,当我selectsearch字段,它扩大了容器的界限:

在这里输入图像说明

我该如何解决这个问题,并select时避免大小/外观变化?

注意:尝试了一些选项与translatesAutoresizingMaskIntoConstraintsclipToBounds选项玩没有成功。 我不是iOS用户界面的专家,所以我希望得到一个准确的答案。 谢谢

根据我的研究,每次你selectSearchBar ,都会提供一个UISearchController 。 这个UISearchController总是试图让searchBar的宽度等于显示UISearchController UIViewController

我的解决scheme是,当UISearchController使SearchBar有错误的框架,再次设置SearchBar框架。 你可以尝试下面的代码。

 @interface ViewController () <UISearchControllerDelegate> @property (nonatomic, strong) UISearchController* searchController; @property (weak, nonatomic) IBOutlet UIView *searchBarContainer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsViewController]; UISearchBar* searchBar = self.searchController.searchBar; self.searchController.delegate = self; searchBar.frame =_searchBarContainer.bounds; [_searchBarContainer addSubview:searchBar]; [_searchBarContainer layoutIfNeeded]; } - (void)willPresentSearchController:(UISearchController *)searchController { [searchController.searchBar addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; } - (void)willDismissSearchController:(UISearchController *)searchController{ [searchController.searchBar removeObserver:self forKeyPath:@"frame"]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { if (object == self.searchController.searchBar) { if (!CGSizeEqualToSize(self.searchController.searchBar.frame.size, _searchBarContainer.frame.size)) { self.searchController.searchBar.superview.clipsToBounds = NO; self.searchController.searchBar.frame = CGRectMake(0, 0, _searchBarContainer.frame.size.width, _searchBarContainer.frame.size.height); } } } @end 

至less,它的工作:)

要么

  • 您可以创build另一个包含SearchBar UIViewController ,然后将其添加到_searchBarContainer,如果您的案例没有任何问题。
  • 使用UISearchBarUITableView而不是UISearchController 。 这更容易处理。

我发现有用的信息。

点击UISearchBar时会调用几个方法。 当这个方法被调用的时候, UISearchBar的框架会改变它的值。

其中一种方法试图填充等于UIViewController的宽度。

尝试在以下方法之一中设置帧值:

searchBarTextDidBeginEditing
searchBarShouldBeginEditing

用这种方法可以覆盖默认值。

再见