0

我正在尝试在表格的标题视图内创建一个带有搜索栏的表格视图。我想使用 searchDisplayController 来管理所有内容。我以编程方式创建了所有内容(我对 IB 感到不舒服)试图设置所有正确的属性,但似乎我遗漏了一些东西,因为当表格出现时我无法编辑文本搜索栏并查看任何动画。这是代码的一部分:

- (void)viewDidLoad {
    [super viewDidLoad];
    UISearchBar *searchBarTMP=[[UISearchBar alloc]init];
    self.searchBar=searchBarTMP;
    [searchBarTMP release];
    self.searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
    self.searchBar.delegate=self;
    self.searchBar.showsScopeBar=YES;
    self.searchBar.keyboardType=UIKeyboardTypeDefault;
    self.searchBar.userInteractionEnabled=YES;
    self.searchBar.multipleTouchEnabled=YES;

    self.searchBar.scopeButtonTitles=[NSArray arrayWithObjects:NSLocalizedString(@"City",@"Scope City"),NSLocalizedString(@"Postal Code",@"Scope PostalCode"),nil];
    self.tableView.tableHeaderView=searchBar;
    self.searchBar.selectedScopeButtonIndex=0;
    self.navigationItem.title=NSLocalizedString(@"Store",@"Table title");

    //SearchDisplayController creation
    UISearchDisplayController *searchDisplayControllerTMP = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
    self.searchDisplayController=searchDisplayControllerTMP;
    [searchDisplayControllerTMP release];
    self.searchDisplayController.delegate=self;
    self.searchDisplayController.searchResultsDelegate=self;
    self.searchDisplayController.searchResultsDataSource=self;  

    //....continue
}

我知道当您单独使用搜索栏时,您必须处理它的委托协议,但我猜测 searchDisplayController 会为您管理,如 Apple 示例代码中所示。(建立与 IB)。

有什么建议吗?谢谢你,安德里亚

4

2 回答 2

0

找到了... 放入表视图的表头后必须写

[self.searchBar sizeToFit];
于 2011-01-07T21:33:15.177 回答
0

如果您使用 ARC,请确保在头文件中为 UISearchDisplayController 创建一个 iVar。

如果您使用以下方法创建 UISearchDisplayController:

UISearchDisplayController* searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchField contentsController:self];

它将由 ARC 释放,它不会调用任何委托方法,并且当您调用self.searchDisplayController(UIViewController 的属性)时,它将是nil.

因此,解决方法是:在您的标头 (.h) 文件中:

@interface MenuViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate> {
        UISearchDisplayController* searchDisplayController;
        UISearchBar *searchField;
        UITableView* tableView;
        NSArray* searchResults;
}

并在实现(.m)文件中:

searchField = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 49)];
searchField.delegate = self;

searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchField contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self;

tableView.tableHeaderView = searchField;
tableView.contentOffset = CGPointMake(0, searchField.frame.size.height);

当这样实现时,您可以在其余代码中调用self.searchDisplayController两者。searchDisplayController

于 2013-06-09T14:49:49.960 回答