2017-09-17 35 views
0

更新到iOS11后,我的searchBar表现很奇怪。激活后,它跳转到屏幕顶部。它像以前一样工作,但我当然希望它保持原位。我试着用google搜索这个行为,但没有任何帮助。有人有同样的问题吗?你做了什么来解决这个问题?更新到iOS11后,我的searchBar表现很奇怪

searchBar in place

searchBar jumped to top

var searchController: UISearchController! 


     override func viewDidLoad() { 
      super.viewDidLoad() 
      // Setup the Search Controller 
      searchController = UISearchController(searchResultsController: nil) 
      searchController.searchResultsUpdater = self 
      searchController.dimsBackgroundDuringPresentation = false 
      searchController.hidesNavigationBarDuringPresentation = false 
      searchController.searchBar.preservesSuperviewLayoutMargins = true 
      searchController.obscuresBackgroundDuringPresentation = false 
      searchController.searchBar.sizeToFit() 
      walkaboutTableView.tableHeaderView = searchController.searchBar 
      searchController.searchBar.barTintColor = matildaLightBlue 
      searchController.searchBar.clipsToBounds = true 
      searchController.searchBar.layer.borderWidth = 2 
      searchController.searchBar.layer.borderColor = UIColor.black.cgColor 
    } 

回答

0

添加搜索控制器实例为导航项目,而不是表头视图可以帮助我解决类似的问题,在我的项目。

if #available(iOS 11, *) { 
    navigationItem.searchController = searchController 
} else { 
    tableView.tableHeaderView = searchController.searchBar 
} 

navigationItem.searchController

navigationItem.hidesSearchBarWhenScrolling

+0

感谢您的答复,但它仍然无法正常工作。实际上,当使用此代码时,根本没有searchBar ... 如果我声明“var searchController:UISearchController!”在viewDidLoad中它保持原位,但是我无法从代码的其他部分到达searchController。 – Stiiv

+0

你可以试试在控制器中将searchController初始化为常量吗? 'let searchController = UISearchController(searchResultsController:nil)' 此外 - 你可以下载一个很好的示例代码项目[这里](https://developer.apple.com/library/content/samplecode/TableSearch_UISearchController/Introduction/Intro。 HTML)来玩。 –

0

鲁斯兰Kolosovskyi的答案是非常好的。另外,如果你想搜索栏更容易访问:

if #available(iOS 11, *) { 
     navigationItem.searchController = searchController 

     navigationItem.hidesSearchBarWhenScrolling = false 
    } else { 
     tableView.tableHeaderView = searchController.searchBar 
    }