Search code examples
ios5uisearchbarxcode-storyboard

How do i hide UISearchbar on load from storyboard


This is more of cosmetic issue.

I have added a searchbar via the storyboard and I want to hide the following with the storyboard.

I was able to do this previously using codes that was before storyboard came into the picture.

Can anyone point me in the right direction if this is achievable using storyboard?

Cheers, Lance


Solution

  • On your storyboard, select your search bar and open the object inspector on the right. In their you will find a property called "hidden". check the box and the object will be hidden when the storyboard is initialized.

    If you ctrl-drag from the search bar and create a property in your view controller, you can then control the hidden flag in code. So you can make it re-appear when you need it, something like:

    self.searchbar.hidden = NO;
    

    Edited 1/2/2013 - Here is a different approach. Checklist:

    a)Add a search bar to your tableview's header view in your storyboard. Link that search bar to a property called searchBar. When you link it, xcode will give it a weak reference, change the weak reference to strong. ex:

    @property (strong, nonatomic) IBOutlet UISearchBar *searchBar; 
    

    b)Add a BOOL property called showSearch to control showing and hiding the search bar.

    @property (nonatomic) BOOL showSearch;
    

    c)Add the following methods to your controller code

    - (void)setShowSearch:(BOOL)showSearch {
    
        _showSearch = showSearch;
    
        if (! _showSearch) {
            self.tableView.tableHeaderView = nil;
        }
        [self.tableView reloadData];
    
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection: (NSInteger)section
    {
        if (self.showSearch && self.tableView.tableHeaderView == nil) {
            return self.searchBar.frame.size.height;
        }
    return 0;
    }
    
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        if (self.showSearch && self.tableView.tableHeaderView == nil) {
           return self.searchBar;
        }
        return nil;
    }
    

    by default this will start with the search bar showing. If you want to start with it hidden, just add the following to your viewDidLoad method:

    self.showSearch = NO;
    

    best of luck and happy new year!