iOS Fix search bar on top of the UITableViewController?

后端 未结 2 815
情话喂你
情话喂你 2020-12-10 05:33

I\'m adding search bar on table header and floating it in scrollViewDidScroll method, but when i scroll without click on search bar(i.e. i go to the view and do

相关标签:
2条回答
  • 2020-12-10 06:06

    There is not a way to maintain the header of a tableView fixed

    1- could use an UIViewController instead of UITableViewController.

    2- add subview (UIView) for header.

    3- and add another subview for the tableview.

    0 讨论(0)
  • 2020-12-10 06:13

    The reason why your searchbar is scrolling with the table contents is that you have put it directly IN the table, thus making it a child header section of the table. and that section ALWAYS scrolls…

    Here is how this this can be achieved. And it is actually quite simple. (The following example relies on Storyboard, but the mechanism is the same whatever you are using) :

    1) Use a UIVIewController and NOT a UITableViewController

    2) Add a UITableView as the child of the parent UIView

    3) Add a UISearchBarController also as a child view of the UIView, NOT as a child of the UITableView (UITableView and UISearchController are siblings)

    you should have the following layout :

    enter image description here

    EDIT : The important thing to remember is to put the UISearchBarController ABOVE the sibling UITableView. Otherwise you may see the UITableView overlap the UISearchBarController when the latter is focused.

    EDIT 2 : BTW, if you are using AutoLayout, remember to set the TOP constraint of the tableView relative to the SearchBar…

    Run it and admire the result.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题