Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchController search bar width not changing

Tags:

ios

swift

ios8

Ran through a quick tutorial with search bars and figured that I could use searchBar.sizeToFit() to autosize the search bar, however the right end of the search bar still extends off of the screen.

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate {

     var searchController = UISearchController(searchResultsController: nil)
     override func viewDidLoad() {
         super.viewDidLoad()
         searchController.searchBar.delegate = self
         searchController.searchResultsUpdater = self
         searchController.dimsBackgroundDuringPresentation = false
         searchController.searchBar.sizeToFit()
         tableView.tableHeaderView = searchController.searchBar
         definesPresentationContext = true
    }}

I've tried to manually set the frame with something like searchController.searchBar.frame = CGRectMake(0, 0, 200, 200) but the width remained off of the screen. The search bar does not exist in the storyboard, however the tableView does.

like image 826
nhyne Avatar asked Oct 19 '22 03:10

nhyne


2 Answers

Needed to set autolayout constraints for the tableView that the search bar was a part of. Setting these fixed the sizing issues.

like image 187
nhyne Avatar answered Oct 22 '22 01:10

nhyne


If you're using Auto layout, then use leading and trailing edges instead of width constraints.

like image 28
simardeep singh Avatar answered Oct 22 '22 01:10

simardeep singh