iOS 11 tableView Header 中的搜索栏在焦点上跳转到屏幕顶部

iOS 11 search bar in tableViewHeader jumps to the top of the screen on focus

关于此主题 here and 已有 2 个未答复的帖子,其中没有人提供解决此问题的可行方法。

第一张图片显示了 iOS 搜索控制器的 10 种行为,您可以在其中看到左侧的层次结构和右侧的红色框内的搜索控制器框架。蓝色中心的视图是 table 中正确显示的视图。

第二张图片显示 iOS 11 行为,其中搜索控制器退出 tableView header 的边界,并移动到没有任何意义的屏幕顶部,因为 table 视图位于距屏幕顶部 230 像素处。

我用来显示所有这些的代码如下(在 viewDidLoad 中):

self.definesPresentationContext = YES;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.searchController.searchBar.clipsToBounds = YES;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.searchBar.placeholder = @"Enter name or email";
[self.searchController.searchBar sizeToFit];

自 iOS11 起,搜索控件成为导航栏的一部分。您将需要如下内容

Objective-C if (@available(iOS 11.0, *)) { self.navigationItem.searchController = searchController } else { self.tableView.tableHeaderView = searchController.searchBar }

Swift

if #available(iOS 11.0, *) {

这是情节提要中视图控制器中 tableView 的约束。

 var tableConstraints: [NSLayoutConstraint]  {
            var constraints = [NSLayoutConstraint]()
            constraints.append(NSLayoutConstraint(item: self.tableViewMyMedia, attribute: .left, relatedBy: .equal,
                                                  toItem: self.view, attribute: .left, multiplier: 1.0, constant: 1.0))
            constraints.append(NSLayoutConstraint(item: self.tableViewMyMedia, attribute: .right, relatedBy: .equal,
                                                  toItem: self.view, attribute: .right, multiplier: 1.0, constant: 1.0))
            constraints.append(NSLayoutConstraint(item: self.tableViewMyMedia, attribute: .top, relatedBy: .equal,
                                                  toItem: self.view, attribute: .top, multiplier: 1.0, constant: 1.0))
            constraints.append(NSLayoutConstraint(item: self.tableViewMyMedia, attribute: .bottom, relatedBy: .equal,
                                                  toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 1.0))
            return constraints
        }

现在添加搜索栏并像这样添加约束

  let search = UISearchController(searchResultsController: nil)
            search.searchResultsUpdater = self
            self.navigationItem.searchController = search
            NSLayoutConstraint.activate(tableConstraints) // important

检查一下,上下滚动时没有跳动。

尝试使用

searchController.hidesNavigationBarDuringPresentation = NO;

结果会让你大吃一惊!