iOS-UISerachBar的基本设置

pragma mark - 搜索框

-(void)createSearchBar
{
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 375, 44)];
    _searchBar.placeholder = @"80万款应用搜搜看";
    _searchBar.delegate = self;
    
    _tableView.tableHeaderView = _searchBar;
}

-(void)changeSearchBarTitle
{
    for(UIView *subview in [_searchBar.subviews[0] subviews])
    {
        if([subview isKindOfClass:[UIButton class]])
        {
            UIButton *button = (UIButton *)subview;
            [button setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self changeSearchBarTitle];
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    searchBar.text = @"";
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    SearchViewController *svc = [[SearchViewController alloc] init];
    svc.keyword = searchBar.text;
    
    [self.navigationController pushViewController:svc animated:YES];
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    searchBar.text = @"";
}

你可能感兴趣的:(iOS-UISerachBar的基本设置)