Search code examples
swiftios11uinavigationitemuisearchcontroller

How to remove the line under the UISearchController on iOS 11?


How can I remove the line under the UISearchController on iOS 11?

I've added the UISearchController using this code:

navigationItem.searchController = searchController

but after doing that there is a weird line under it:

enter image description here

Any advice on how to remove the line or at least choose its color would be greatly appreciated.


Solution

  • Here is another solution, a weak one but it could be useful in specific use-case.

    extension UISearchController {
    
        var hairlineView: UIView? {
            guard let barBackgroundView = self.searchBar.superview?.subviews.filter({ String(describing: type(of: $0)) == "_UIBarBackground" }).first
            else { return nil }
    
            return barBackgroundView.subviews.filter({ $0.bounds.height == 1 / self.traitCollection.displayScale }).first
        }
    }
    

    With that extension, you only have to write the following code in the viewWillLayoutSubviews method of your view controller:

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    
        // Remove hairline from the searchBar.
        self.navigationItem.searchController?.hairlineView?.isHidden = true
    }
    

    Important:

    Please note that this solution is really weak and can break with future iOS updates.
    Furthermore, $0.bounds.height == 1 / self.traitCollection.displayScale is unsafe and I advise you to use a proper float comparison method.