1

I have followed the google places autocomplete example to add a searchbar to a view under the nav bar. It shows ok but even with the line below the seachbar hides under the larger iOS11 nav bar. I have enabled safeAreaLayoutGuide in AutoLayout.

Search bar inactive Search bar active

I have the code I am using.

override func viewDidLoad() {
 super.viewDidLoad()

 resultsViewController = GMSAutocompleteResultsViewController()
 resultsViewController?.delegate = self

 navigationController?.navigationBar.isTranslucent = false
 self.navigationController?.navigationBar.prefersLargeTitles = true

 searchController = UISearchController(searchResultsController: resultsViewController)
 searchController?.searchResultsUpdater = resultsViewController
 searchController?.searchBar.sizeToFit()
 searchController?.hidesNavigationBarDuringPresentation = false

 let navBarBounds = self.navigationController!.navigationBar.frame.size
 let statusHeight = UIApplication.shared.statusBarFrame.height

 let subView = UIView(frame: CGRect(x: 0, y: navBarBounds.height + statusHeight, width: navBarBounds.width, height: 45.0))

 // This makes the view area include the nav bar even though it is opaque.
 // Adjust the view placement down.
 self.extendedLayoutIncludesOpaqueBars = true
 self.edgesForExtendedLayout = .top

 // When UISearchController presents the results view, present it in
 // this view controller, not one further up the chain.
 definesPresentationContext = true

 subView.addSubview((searchController?.searchBar)!)
 view.addSubview(subView)

 if #available(iOS 11, *) {
   let guide = view.safeAreaLayoutGuide
   NSLayoutConstraint.activate([
     subView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
     guide.bottomAnchor.constraintEqualToSystemSpacingBelow(subView.bottomAnchor, multiplier: 1.0)
     ])

 } else {
   let standardSpacing: CGFloat = 8.0
   NSLayoutConstraint.activate([
    subView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
    bottomLayoutGuide.topAnchor.constraint(equalTo:  subView.bottomAnchor, constant: standardSpacing)
     ])
  }
 }
}
SashaZ
  • 393
  • 7
  • 20

0 Answers0