1. 程式人生 > >iOS 開發搜尋框

iOS 開發搜尋框

搜尋框製作:

1.遵守協議:

    UISearchBarDelegate

2.建立搜尋:

    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,44)];

    searchBar.placeholder = @"60萬款應用搜搜看";

    searchBar.delegate = self;

    self.tableView.tableHeaderView = searchBar;

3.實現代理方法:

#pragma mark - UISearchBar代理

//開始輸入文字的時候呼叫

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar

{

    //顯示取消按鈕

    searchBar.showsCancelButton = YES;

    //cancel改成中文

    UIView *firstSub = [searchBar.subviews firstObject];

    for (UIView *sub in firstSub.subviews) {

        if ([sub isKindOfClass:NSClassFromString(@"UINavigationButton")]) {

            UIButton *btn = (UIButton *)sub;

            //修改背景圖片

            [btn setBackgroundImage:[UIImage imageNamed:@"buttonbar_action"] forState:UIControlStateNormal];

            //修改文字

            [btn setTitle:@"取消" forState:UIControlStateNormal];

            //修改字型大小

            btn.titleLabel.font = [UIFont systemFontOfSize:14];

        }

    }

}

//點選取消按鈕時的操作

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

{

    //隱藏鍵盤

    [searchBar resignFirstResponder];

    //隱藏取消按鈕

    searchBar.showsCancelButton = NO;

}

//點選鍵盤的search按鈕呼叫

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{

    //隱藏鍵盤

    [searchBar resignFirstResponder];

    //隱藏取消按鈕

    searchBar.showsCancelButton = NO;

    //跳轉到搜尋結果介面

    CHSearchController *ctrl = [[CHSearchController alloc] init];

    //關鍵字

//    ctrl.keyword = searchBar.text;

//    //型別

//    ctrl.type = SearchTypeLimit;

    self.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:ctrl animated:YES];

    self.hidesBottomBarWhenPushed = NO;

}