iOS - 使用UISearchDisplayController和UISearchBar,它是UIToolbar中的UIBarButtonItem

Ram*_*eln 6 uitoolbar uisearchbar uisearchdisplaycontroller ios

有没有人尝试使用UISearchDisplayController和UISearchBar,它是UIToolbar中的UIBarButtonItem?

我会很感激如何成功地做到这一点.

目前,每当搜索控制器弹出时,它会重绘UISearchBar,我很难保持与UIToolbar相似的外观

小智 5

通常,您不希望在工具栏中放置搜索栏,但是,您似乎想要执行类似于我所做的操作.

所以这就是我如何做到的,它可能被称为黑客,但它就像一个魅力:)

首先,您必须在界面生成器中进行设置,如下所示:

在此输入图像描述

请注意,搜索不是工具栏的子项,而是在上面.

搜索栏应具有"清晰颜色"背景和灵活的左,右和宽度自动调整遮罩.

您在工具栏下方放置了一个带有黑色背景的1像素标签,即.[x = 0,y = 44,宽度= 320或帧宽,高度= 1],还有灵活的左,右和宽度自动调整遮罩.这是在搜索显示控制器显示表格后隐藏您获得的一个可见像素视图.没有它就试试看我的意思.

你设置任何工具栏项目,并确保有他们的出口,因为你将需要这些.

现在代码......

当你开始搜索:

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    // animate the search bar to the left ie. x=0
    [UIView animateWithDuration:0.25f animations:^{
        CGRect frame = controller.searchBar.frame;
        frame.origin.x = 0;
        controller.searchBar.frame = frame;
    }];
    // remove all toolbar items
    [self.toolbar setItems:nil animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

当你结束搜索

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    // animate search bar back to its previous position and size
    // in my case it was x=55, y=1
    // and reduce its width by the amount moved, again 55px
    [UIView animateWithDuration:0.25f 
                          delay:0.0f
                        // the UIViewAnimationOptionLayoutSubviews is IMPORTANT,
                        // otherwise you get no animation
                        // but some kind of snap-back movement 
                        options:UIViewAnimationOptionLayoutSubviews 
                     animations:^{
                         CGRect frame = self.toolbar.frame;
                         frame.origin.y = 1;
                         frame.origin.x = 55;
                         frame.size.width -= 55;
                         controller.searchBar.frame = frame;
                     } 
                     completion:^(BOOL finished){
                         // when finished, insert any tool bar items you had
                         [self.toolbar setItems:[NSArray arrayWithObject:self.currentLocationButton] animated:YES];
                     }];
}
Run Code Online (Sandbox Code Playgroud)

有了这个我得到以下一个很好的动画:)

在此输入图像描述

在此输入图像描述