iosswiftuisearchbarautoresizingmask

iOS SearchController Searchbar does not work after adding constraint programmatically


I have an iOS project whereby the SearchController's SearchBar is added to the view as a subview:

let subView = UIView(frame: CGRect(x: 0, y: 65.0, width: 350.0, height: 45.0))
subView.addSubview((self.searchController.searchBar))
self.view.addSubview(subView)

As shown in the screenshot below, the searchbar is partially obscured by the navigation bar:

enter image description here

As such, I added the following constraint:

subView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([subView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)])

The searchbar is now positioned correctly below the navigation bar as shown:

enter image description here

However, I'm now not able to click onto the searchbar to input any text. How can I resolve this?


Solution

  • How I resolved this at the end.

    I still made use of a subView for the searchbar. But this time, instead of giving a fixed value for y, I used the heights of the safeArea and the navigation bar as shown:

     let window = UIApplication.shared.windows.first
     let safeheight = window?.safeAreaInsets.top
            
     let navHeight = self.navigationController?.navigationBar.frame.height
            
     let subView = UIView(frame: CGRect(x: 0, y: safeheight! + navHeight!, width: 350.0, height: 45.0))
     subView.addSubview((self.searchController.searchBar))
     self.view.addSubview(subView)
    

    This time, the searchbar was positioned correctly and worked perfectly.