Search code examples
iosswiftxcodeuisearchcontrollervisual-glitch

How to fix UISearchController search bar resizing when focused?


I am trying to implement a UISearchController with a UITableView inside of a small popup screen like this: Image displaying a popup with a UITableView and UISearchController.
However, when the search bar is focused, it moves up and becomes wider, as shown here: Image displaying a glitched search bar.
I have found one other post about this issue here, but the accepted solution did not seem to fix the problem.
For reference, I am using a modal segue displaying over full screen. There is a content view in which the tableView and titleLabel are subviewed. Here is the relevant code for the popup view controller.

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var titleLabel: UILabel!

var items = ["Test", "oewrghp", "wopqet", "vbsjadsf", "rweoghp", "bmwehth", "pqeojnh"]
var filteredItems = [String]()
let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissTapGesture(gesture:)))
    view.addGestureRecognizer(tapGesture)
    view.backgroundColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 0.3)

    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.barTintColor = .white
    searchController.searchBar.backgroundColor = .clear
    searchController.searchBar.delegate = self
    searchController.obscuresBackgroundDuringPresentation = false

    titleLabel.text = "Search"

    tableView.tableHeaderView = searchController.searchBar
    tableView.delegate = self
    tableView.dataSource = self
    tableView.reloadData()
    tableView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))))

    // Do any additional setup after loading the view.
}

Solution

  • Use a UISearchBar instead of a UISearchController

    Something like:

    let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44))
    

    Hope this helps someone!