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

Add*_*dev 2 xcode objective-c interface-builder ios

我正在尝试在我的应用程序 UI 中放置一个 UISearchController。布局是:

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

在此处输入图片说明

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

我的代码如下:

self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsViewController];
UISearchBar* searchBar = self.searchController.searchBar;
searchBar.frame =_searchBarContainer.bounds;
[_searchBarContainer addSubview:searchBar];
[_searchBarContainer layoutIfNeeded];
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

但是当我选择搜索字段时,它会将栏扩展到容器的边界上:

在此处输入图片说明

如何解决这个问题并避免选择时的尺寸/外观变化?

注意:尝试了一些使用translatesAutoresizingMaskIntoConstraints和 的 clipToBounds选项,但没有成功。我不是 iOS UI 的专家,所以我希望得到准确的答案。谢谢

tru*_*duc 5

根据我的研究,每次选择 时SearchBarUISearchController都会显示一个。这UISearchController总是试图使searchBar的宽度等于UIViewController呈现的宽度UISearchController

我的解决方案是当UISearchControllermakeSearchBar有错误的框架时,SearchBar再次设置'frame。您可以在下面尝试此代码。

@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
Run Code Online (Sandbox Code Playgroud)

至少,它有效:)

或者

  • 如果您的案例对此没有任何问题,您可以创建另一个UIViewController包含SearchBar在此之后将其添加到 _searchBarContainer 的内容。
  • 使用UISearchBarUITableView代替UISearchController。更容易处理。