我目前正在开展一个项目,我必须通过NSArray进行过滤(显示在UITableView中)。问题是,既没有XIB文件也没有故事板。 我的问题是(我已经设置了谓词和搜索方法et.c),如何使用代码让我的程序中显示SearchBar - 而且我需要能够使用它。 我对这个问题的一些帮助感到非常高兴,因为我找到的每个教程都使用了storyboard或xibs:(
非常感谢你! 顺便说一句,这是我到目前为止关于搜索栏的两种方法,TableView也已经设置好了。
-(void) filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", searchText];
self.searchResults = [self.array filteredArrayUsingPredicate:predicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
答案 0 :(得分:0)
如果没有XIB文件而没有Storyboard,它会在代码中的某个地方(可能在viewDidload中)启动,看起来像这样。
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
searchBar.delegate = self;
//etc..
现在首先在界面中添加一个属性
@property (nonatomic, strong)UISearchBar *searchBar;
并在viewDidLoad中更改此行:
self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
现在,您可以在代码中的任何位置使用self.searchBar
。
编辑:
并且不要忘记将它添加到界面中,如果它还没有:
@interface ViewController () <UISearchBarDelegate, UISearchDisplayDelegate>
答案 1 :(得分:0)
您可以这样做:
在你的.h中添加:
@property (nonatomic,strong) UISearchBar *searchBar;
在viewDidLoad
方法
self.searchBar = [[UISearchBar alloc]init];
self.searchBar.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);
self.searchBar.delegate = self;
//Customize the searchBar
[self.view addSubview:self.searchBar];
每当您想要搜索时,请按键盘内的搜索按钮。执行此操作时将调用代理。像这样,
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
//Do some search
}
您可以使用searchBar.text
属性访问输入的文本。我假设您已经实施了相关协议。