2

I have added an UISearchBar to my UITableView.

// Search Bar
var leftPosSearchBar: CGFloat = 0
if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone) { leftPosSearchBar = 4 }
self.searchBar = UISearchBar(frame: CGRect(
    x: max(leftPosSearchBar, self.tableView.contentOffset.x + self.tableView.contentInset.right), 
    y: max(0, self.tableView.contentOffset.y + self.tableView.contentInset.top), 
    width: self.view.bounds.width, height: 45))
let tableHeaderView: UIView = UIView(frame: self.searchBar.frame)

tableHeaderView.addSubview(self.searchBar)
tableHeaderView.bringSubviewToFront(self.searchBar)

self.tableView.tableHeaderView = tableHeaderView
self.searchBar.searchBarStyle = UISearchBarStyle.Prominent
self.searchBar.delegate = self
self.searchBar.returnKeyType = UIReturnKeyType.Done
self.searchBar.enablesReturnKeyAutomatically = false
self.searchBar.translucent = false

Also added this short snippet to "fix" the UISearchBar on top on scroll.

func scrollViewDidScroll(scrollView: UIScrollView) {
    var searchBarFrame:CGRect = self.searchBar.frame
    searchBarFrame.origin.y = max(0, 
        scrollView.contentOffset.y + scrollView.contentInset.top)
    self.searchBar.frame = searchBarFrame
}

Everything works fine until i uses sections in my UITableView. Then the sections get layered over the UISearchBar and stick at the top of the UITableView. It should get sticked under the UISearchBar.

enter image description here

Matt S
  • 14,976
  • 6
  • 57
  • 76
Kevin Lieser
  • 951
  • 1
  • 9
  • 25

1 Answers1

0

Add bringSubviewToFront inside scrollViewDidScroll.

tableHeaderView.bringSubviewToFront(searchBar)

I'm doing something similar but with a UIView, and that works for me.