1. 程式人生 > >iOS自定義UISearchBar,簡單、方便、好用

iOS自定義UISearchBar,簡單、方便、好用

本文首發地址
可惡的UI非要搞一個和系統的UISearchBar的不一樣的效果,但是系統自帶的用實現不了效果,就自能自定義了。

把一個UISearchBar放到UINavigationBar上。並且還要有搜尋的結果在整個頁面上。。。

先看看效果圖
這裡寫圖片描述

HZSearchBar

自定義searcher,完全模仿系統樣式

選擇遵循協議

  1. CustomsearchResultsUpdater

    及時篩選代理同系統的searchResultsUpdater代理一樣的用法。

  2. CustomSearchBarDataSouce
    設定資料來源

    // 設定顯示列的內容
    -(NSInteger)searchBarNumberOfRowInSection;\
    // 設定顯示沒行的內容
    -(NSString *)CustomSearchBar:(CustomSearchBar *)searchBar titleForRowAtIndexPath:(NSIndexPath *)indexPath;

    設定每行顯示的圖片

    // 每行圖片
    -(NSString *)CustomSearchBar:(CustomSearchBar *)searchBar imageNameForRowAtIndexPath:(NSIndexPath *)indexPath;
  3. CustomSearchBarDelegate
    設定點選效果和監聽取消按鈕動作

    // 點選每一行的效果
    - (void)CustomSearchBar:(CustomSearchBar
    *)
    searchBar didSelectRowAtIndexPath:(NSIndexPath *)indexPath; -(void)CustomSearchBar:(CustomSearchBar *)searchBar cancleButton:(UIButton *)sender;

新增HZSearchBar(以新增到導航欄為例)

    self.customSearchBar = [CustomSearchBar show:CGPointMake(0, 0) andHeight:SEMHEIGHT];
    self.customSearchBar.searchResultsUpdater
= self; self.customSearchBar.DataSource = self; self.customSearchBar.delegate = self; [self.navigationController.view insertSubview:self.customSearchBar aboveSubview:self.navigationController.navigationBar];

代理的使用

/**第一步根據輸入的字元檢索 必須實現*/
-(void)CustomSearch:(CustomSearchBar *)searchBar inputText:(NSString *)inputText {
    [self.resultFileterArry removeAllObjects];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",inputText];
    NSArray * arry = [self.myData filteredArrayUsingPredicate:predicate];
    for (NSString * taxChat in arry) {
        [self.resultFileterArry addObject:taxChat];
    }
}
// 設定顯示列的內容
-(NSInteger)searchBarNumberOfRowInSection {
    return self.resultFileterArry.count;
}
// 設定顯示沒行的內容
-(NSString *)CustomSearchBar:(CustomSearchBar *)menu titleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.resultFileterArry[indexPath.row];
}
- (void)CustomSearchBar:(CustomSearchBar *)segment didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"---->>>>>>>>>%ld",indexPath.row);
}

-(void)CustomSearchBar:(CustomSearchBar *)segment cancleButton:(UIButton *)sender {

}
-(NSString *)CustomSearchBar:(CustomSearchBar *)searchBar imageNameForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"Search_noraml";
}

各位看官如有不明白的地方可以檢視Demo或者新增洲洲哥的QQ號:1290925041

還可以

關注洲洲哥的公眾號,提高裝逼技能就靠他了

這裡寫圖片描述