3

我在我的 TopBar.m 中这样写 UISearchBar:

_tempSearchBar =[[UISearchBar alloc]initWithFrame:CGRectMake(44, 0, 320 - 44, 43)];
_tempSearchBar.barStyle=UIBarStyleDefault;
_tempSearchBar.placeholder=@"搜索";
[self addSubview:_tempSearchBar];

结果是这样的,没错。 在此处输入图像描述

然后我在另一个类中编写 UISearchDisplayController ,如下所示:

_topBar.tempSearchBar.delegate = self;    
_searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_topBar.tempSearchBar contentsController:self];
[_searchDisplayController setDelegate:self];
[_searchDisplayController setSearchResultsDataSource:self];

UISearchBarDelegate 是这样的:

#pragma mark -
#pragma mark UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [_searchDisplayController setActive:YES animated:YES];
}

当我单击 UISearchBar 时,它显示为这样,searchBar 的框架发生了变化。为什么? 在此处输入图像描述

当我取消 UISearchDisplayController 它是这样的: 在此处输入图像描述

为什么改变框架?宽度由 UISearchDisplayController 从 320-44 更改为 320?
谢谢。

4

4 回答 4

12

UISearchDisplayController 将搜索栏扩展到其父视图的宽度。我找到的最简单的解决方案是将搜索栏放在另一个具有我正在寻找的宽度的 UIView 中。

于 2012-11-09T19:35:39.227 回答
5

searchBar 的框架是由 UIKit 改变的,所以我自己把 searchBar 的框架改回来了。

我在下面的委托中更改了 searchBar 的框架。

一个是 UISearchBar 的委托:

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    [searchBar setFrame:CGRectMake(44, 0, 320 - 44, 43)];
}

另一个是 UISearchDisplayController 的委托:

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller{
    [controller.searchBar setFrame:CGRectMake(44, 0, 320 - 44, 43)];
    [self.searchDisplayController.searchResultsTableView setDelegate:self];
}

它可以工作,我可以获得正确的框架,但是当我单击 searchBar 时,它会有点晃动。

这不是最好的方法,但它可以工作。有没有人有更好的方法?

更新:我已经调试了 UISearchBar 和 UISearchDisplayController 几个小时,但它有一个小错误:当我 endEditing 时 searchBar 的宽度将变为 320px,然后将变为我的宽度。我无法更改 cancelButton 的背景颜色。所以我写了一个自定义的 SearchDisplayController,有一个 UISearchBar 属性和一个 UITableView 属性。这对我来说很有用。

于 2012-10-16T10:20:06.203 回答
0

调用委托方法

- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    [controller.searchBar setFrame:CGRectMake(0,31, 320 , 43)];
    [self.searchDisplayController.searchResultsTableView setDelegate:self];
} 
于 2015-06-09T07:55:58.870 回答
-1

您可以使用- (void)setShowsCancelButton:animated处理 searchBar 的取消按钮: 如果您不想显示取消按钮(因为取消按钮会更改 searchBar 的框架),只需在委托中编写

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{   

    [searchBar setShowsCancelButton:NO animated:YES];
}

更新:

唯一可能的解决方案似乎是从 SearchBar 视图层次结构中找到取消按钮并将其隐藏。

for (UIView *possibleButton in searchBar.subviews)
{
    if ([possibleButton isKindOfClass:[UIButton class]])
    {
        UIButton *cancelButton = (UIButton*)possibleButton;
        cancelButton.hidden = YES;
        break;
    }
}
于 2012-10-16T05:56:05.653 回答