UISearchController 的搜索栏在搜索完成后向下移动

UISearchController's Search Bar shifting down once search is complete

我在 collection 视图的 header 部分添加了一个搜索栏以及两个按钮,为了完成此操作,我添加了一个视图(我在其中添加了搜索栏) 及其下方的两个按钮。如下图所示。

- (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    _headerView= [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
    [_headerView.searchView addSubview:self.searchController.searchBar];
    return _headerView;

}

下面是我在 ViewDidLoad 方法中添加的行

  self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = YES;
    self.searchController.searchBar.delegate = self;
    self.definesPresentationContext = YES;
    [self.searchController.searchBar sizeToFit];

每当我使用搜索栏进行搜索,然后在搜索完成后将其关闭时,搜索栏会向下移动。

长期以来我一直无法解决这个搜索栏移动问题,关于如何避免这种情况的任何线索,而且在移动搜索栏后不再响应。

这是布局问题。虽然可以通过此方法将搜索栏视图的大小移回原始大小来解决

 - searchBarTextDidEndEditing: 

示例:

在您的 .h 文件中,

@property (nonatomic) CGRect originalViewSize;

在您的 .m 文件中,

- (void) viewDidAppear:(BOOL)animated
{
self.originalViewSize = self.searchController.searchBar.frame;
}


- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
self.searchController.searchBar.frame = self.originalViewSize ;
}

我能够通过以下方法解决此问题,方法是将其从超级视图中删除并重新添加到视图中。

- (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    _headerView= [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"RequestHeaderView" forIndexPath:indexPath];
    [self.searchController.searchBar removeFromSuperview];
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;
    self.definesPresentationContext = YES;
    [self.searchController.searchBar sizeToFit];
    [_headerView.searchView addSubview:self.searchController.searchBar];
    return _headerView;
}