1

I am adding a searchBar to the header of my UITableView and want to be able to use it while user is scrolling through the the cells.

I have tried everything such as setting the style to UITableViewStyleGrouped but it didn't solve my problem.

here is the code

var searchController: UISearchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar

any reason why is the header stays at the stop?

Siyavash
  • 970
  • 9
  • 23
  • @conarch not a helpful answer but it doesn't have anything to do with searchBar. The problem is with the header as it should scroll with while scrolling the contents – Siyavash Sep 28 '17 at 22:22
  • I assumed the search bar b/c that's the code you presented. I mean, you've assigned it AS the table header. It's the TABLE header, so it shouldn't scroll. – ghostatron Sep 28 '17 at 22:23
  • @conarch I am presenting the searchBar in the header view so even if I add a empty view I would get the same result . – Siyavash Sep 28 '17 at 22:24
  • Actually, I thoroughly apologize @Slyavash, I'm in a snarky mood and should not have commented. I do think the table is behaving as intended, but I'm going to delete my earlier comments. Sorry! :-( – ghostatron Sep 28 '17 at 22:26
  • @conarch haha its okay :D , but i think tableview is not behaving as it should have been because if you look at the section header it will scroll as you scroll to the next section – Siyavash Sep 28 '17 at 22:28
  • @ViniApp unfortunately thats for navigation bar and item – Siyavash Sep 28 '17 at 23:10
  • sorry, please check https://stackoverflow.com/questions/31702413/how-to-prevent-search-bar-from-disappearing-on-scroll-ios-swift – Vini App Sep 28 '17 at 23:10

2 Answers2

0

I'm not sure if you're only looking for a programatic solution, but through Interface Builder you can put a Search Bar above the UITableView.

enter image description here

0

If you are using iOS 11 then you can put the UISearchBar in the UINavigationBar using the following code. The UISearchBar will always be visible even if you scroll the UITableView.

class DishesTableViewController : UITableViewController, UISearchResultsUpdating {

    func updateSearchResults(for searchController: UISearchController) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchController = UISearchController(searchResultsController: self)
        searchController.searchResultsUpdater = self

        self.navigationItem.searchController = searchController
        self.navigationItem.hidesSearchBarWhenScrolling = false 
    }

enter image description here

azamsharp
  • 19,710
  • 36
  • 144
  • 222