答案 0 :(得分:-1)
(1)在视图顶部的XIB中添加UISearchBar
,其宽度等于其父视图。添加所需的约束。
(2)设置IBOutlet
并将代理人分配给该搜索栏。
(3)实施以下委托方法:
# pragma mark
# pragma mark - SearchBar delegate
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBarWatches resignFirstResponder];
searchBarWatches.text = @"";
[UIView animateWithDuration:0.25 animations:^{
searchBarWatches.alpha = 0.0;
} completion:^(BOOL finished) {
[searchBarWatches setHidden:TRUE];
searchBarWatches.alpha = 1.0;
}];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
// searchBarTextDidBeginEditing
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
strSearchText = @"";
[self searchWatchWithString:strSearchText];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
searchText = [searchText stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([searchText isEqualToString:strSearchText]) {
return;
}
if([searchText length] > 0) {
strSearchText = searchText;
} else {
strSearchText = @"";
}
[self searchWatchWithString:strSearchText];
}
-(void)searchWatchWithString:(NSString *)strSearch
{
if([strSearch length] > 0)
{
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:....];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:....];
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:....];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2, predicate3]];
[[self.fetchedResultsController fetchRequest] setPredicate:predicate];
}
else
{
// Empty string
}
[self performFetch];
[self reloadTableViewAnimated:TRUE];
}
-(void)reloadTableViewAnimated:(BOOL)animated
{
if(animated) {
[tblProducts reloadSections:[NSIndexSet indexSetWithIndex:0]];
} else {
[tblProducts reloadData];
}
}
(4)点击搜索按钮,显示搜索栏:
- (IBAction)btnSearchPressed:(id)sender
{
[searchBarWatches setHidden:FALSE];
[self.view bringSubviewToFront:searchBarWatches];
[searchBarWatches becomeFirstResponder];
}