iOS custom search bar in navigation bar with animation?

1.9k Views Asked by At

I know the question regarding adding search bar in navigation bar is asked many times here(and i know the process). But my problem is that i have to show search bar with custom background and it must present/hide with an animation when i click on button added to right of navigation bar. Before present search bar

enter image description here

the final UI would like to(after click on search icon) -

like this png

Any help would be appreciated.

Code is

//search bar
    searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width-10-60, 44)];
   // searchBar.translucent = NO;
    //searchBar.barTintColor = [UIColor clearColor];
    searchBar.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar   addSubview:searchBar];

    float delta = searchBar.frame.size.width;
    searchBar.frame = CGRectOffset(searchBar.frame, -delta, 0.0);
    searchBar.hidden = YES;
-(void)rightbuttonPressed
{
    // get the width of the search bar
    float delta = searchBar.frame.size.width;
    // check if toolbar was visible or hidden before the animation
    BOOL isHidden = [searchBar isHidden];

    // if search bar was visible set delta to negative value
    if (!isHidden) {
        delta *= -1;
    } else {
        // if search bar was hidden then make it visible
        searchBar.hidden = NO;
    }

    // run animation 0.7 second and no delay
    [UIView animateWithDuration:0.7 delay: 0.0 options: UIViewAnimationOptionCurveEaseIn animations:^{
        // move search bar delta units left or right
        searchBar.frame = CGRectOffset(searchBar.frame, delta, 0.0);
    } completion:^(BOOL finished) {
        //if the bar was visible then hide it
        if (!isHidden) {
            searchBar.hidden = YES;
        }
    }];
}
1

There are 1 best solutions below

1
On

Don't add the search bar as a subview on the navigation bar. Instead set it as the titleView of the navigationItem of the current view controller.

Add the search bar in a UIView, and assign the view to titleView. Animate the search bar inside this view as you normally would. For background, UISearchBar has a backgroundImage property.