我目前正在进行一个项目,在这个项目中,我必须通过一个NSArray (显示在UITableView中)进行过滤。问题是,这里既没有XIB文件,也没有故事板。我的问题是(我已经设置了谓词和搜索方法等),如何使SearchBar只使用代码在我的程序中显示-并且我需要能够使用它。我很高兴能在这个问题上提供一些帮助,因为我发现的每一个教程都使用故事板或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;}
发布于 2014-06-25 15:08:24
你可以这样做:
在您的.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属性访问输入的文本。我假设你已经执行了相关的协议。
发布于 2014-06-25 15:05:20
如果没有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>https://stackoverflow.com/questions/24411774
复制相似问题