在导航栏IOS7中显示搜索栏

时间:2016-05-17 05:11:36

标签: ios swift uinavigationbar uisearchbar

我想问一下当我点击IOS 7中的搜索图标时如何在导航栏中显示搜索栏,我浏览的几乎所有教程都不支持IOS 7,也许你可以就如何实现这些功能。

这是我们用户界面的截图:

enter image description here

1 个答案:

答案 0 :(得分:-1)

(1)在视图顶部的XIB中添加UISearchBar,其宽度等于其父视图。添加所需的约束。

enter image description here

(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];
}