带动画的导航栏中的iOS自定义搜索栏?

时间:2015-06-16 08:47:33

标签: ios objective-c uinavigationbar uisearchbar

我知道在这里多次询问有关在导航栏中添加搜索栏的问题(我知道这个过程)。但我的问题是我必须显示具有自定义背景的搜索栏,当我点击导航栏右侧添加的按钮时,它必须呈现/隐藏动画。 在目前的搜索栏之前

enter image description here

最终用户界面想要(点击搜索图标后) -

like this png

任何帮助都将不胜感激。

代码是

//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 个答案:

答案 0 :(得分:0)

不要将搜索栏添加为导航栏上的子视图。而是将其设置为当前视图控制器的navigationItem的titleView。

在UIView中添加搜索栏,并将视图分配给titleView。像往常一样为此视图中的搜索栏设置动画。对于后台,UISearchBar具有backgroundImage属性。