1
votes

I currently have a UISearchBar in a normal UIViewController. The SearchBar is more or less in the middle of the UIView, and when I click to enter some text, my tableView completely overlaps the searchBar, and I can't click on the clear/cancel button: I don't see the search bar anymore. When I move my searchBar completely to the top of my view, it's perfect. But I do it with Storyboard. How can I do exactly the same programmatically? Move the SearchBar to the top top of the view.

Thanks a lot for your help

2

2 Answers

0
votes

I would recommend looking into UISearchController (iOS 8+). From the Apple Docs:

The UISearchController class defines an interface that manages the presentation of a search bar in concert with the search results controller’s content.

The Apple docs can be found here.

If you insist on doing it manually, you could try setting up an Auto Layout constraint as follows to place the SearchBar at the top of the TableView always:

 [self addConstraint:[NSLayoutConstraint constraintWithItem:_searchBar
                                             attribute:NSLayoutAttributeBottom
                                             relatedBy:NSLayoutRelationEqual
                                                toItem:_myTableView
                                             attribute:NSLayoutAttributeTop
                                            multiplier:1.0
                                              constant:0.0]];
0
votes

You have 3 options:

  1. [self.view insertSubview:yourSearchBar aboveSubview:yourTableView];

  2. [parentView bringSubviewToFront:yourSearchBar];

  3. [self.view insertSubview:yourSearchBar atIndex:0];

Btw - All the problems with the view that jumps back and forth caused when you create them with the storyboard, so its much better to do it programmatically.