iOS - 高仿通訊錄之商品索引排序搜索

項(xiàng)目中像一些商品搜索類界面, TableView添加右側(cè)索引的使用越來越多, 的確用戶體驗(yàn)提高了許多.

大致思路:

  1. 添加并設(shè)置右側(cè)索引
  2. 自定義漢字轉(zhuǎn)化成拼音文件,通過拼音去匹配首字母
  3. 將庫存數(shù)據(jù)按照索引分組排序
  4. 添加搜索功能
  5. 搜索界面復(fù)用庫存界面, 增加標(biāo)識判斷顯示界面

一. 添加并設(shè)置右側(cè)索引

設(shè)置右側(cè)索引數(shù)組:

// 索引標(biāo)題數(shù)組
@property (nonatomic, strong) NSMutableArray * indexArr;

 // 設(shè)置右側(cè)索引數(shù)組
 _indexArr = [[NSMutableArray alloc]init];
for(char c = 'A'; c<='Z'; c++) {
     [_indexArr addObject:[NSString stringWithFormat:@"%c", c]];
 }
 [_indexArr addObject:[NSString stringWithFormat:@"#"]]; // 

設(shè)置右側(cè)索引字體顏色:

 self.tableView.sectionIndexColor = [UIColor grayColor];

設(shè)置右側(cè)索引背景色:

self.tableView.sectionIndexBackgroundColor = [UIColor whiteColor]; 

設(shè)置標(biāo)簽數(shù)(其實(shí)就是分區(qū)數(shù)目):

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return indexArr.count;
}

顯示每組標(biāo)題索引 (如果不實(shí)現(xiàn) 就不顯示右側(cè)索引):

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    return indexArr;
}

設(shè)置索引section的高度:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

返回每個索引的內(nèi)容:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return indexArr[section];
}

這時候基本的索引展現(xiàn)了, 需要響應(yīng)點(diǎn)擊索引則添加下面方法 及 將數(shù)據(jù)分類展現(xiàn).
響應(yīng)點(diǎn)擊索引時的委托方法(點(diǎn)擊右側(cè)索引表項(xiàng)時調(diào)用):

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
      NSInteger count = 0;
    for(NSString *character in _toBeReturned) {
        if([character isEqualToString:title]) {
            return count;
        }
        count ++;
    }
    return 0;
}

二. 自定義漢字轉(zhuǎn)化成拼音文件,通過拼音去匹配首字母

將數(shù)據(jù)分類展現(xiàn)則是一個大問題!
因?yàn)楹笈_返回給我們是所有數(shù)據(jù),沒法通過分區(qū)去控制各個分區(qū)數(shù)據(jù)的數(shù)據(jù), 這個時候就考慮到漢字轉(zhuǎn)化成拼音,然后通過拼音去匹配首字母然后排序解決這個問題.

封裝一個漢字轉(zhuǎn)化成拼音YYPChineseToPinyin 文件:
1.根據(jù)漢字返回漢字的拼音:

/**
 *  根據(jù)漢字返回漢字的拼音
 *
 *  @param word 一個漢字
 *
 *  @return 拼音的字符串
 */
+ (NSString *)transformChinese:(NSString *)word {
    NSMutableString *pinyin = [word mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    
    return [pinyin uppercaseString];
}

2.比較對象數(shù)組:

/**
 *  排序后的首字母(不重復(fù))用于tableView的右側(cè)索引
 *
 *  @param objectArray  需要排序的對象數(shù)組
 *  @param key          需要比較的對象的字段
 *
 *  @return 排序后的首字母(不重復(fù))
 */
+ (NSMutableArray *)indexWithArray:(NSArray *)objectArray Key:(NSString *)key;

/**
 *  給對象數(shù)組排序
 *
 *  @param objectArray 需要排序的對象數(shù)組
 *  @param key       需要比較的對象的字段
 *
 *  @return 根據(jù)字段排序后的對象數(shù)組(同首寫字母的在一個數(shù)組中)
 */
+ (NSMutableArray *)sortObjectArray:(NSArray *)objectArray Key:(NSString *)key;

3.比較字符串?dāng)?shù)組:

/**
 *  排序后的首字母(不重復(fù))用于tableView的右側(cè)索引
 *
 *  @param stringArr 需要排序的字符數(shù)組
 *
 *  @return 排序后的首字母(不重復(fù))
 */
+ (NSMutableArray*)indexArray:(NSArray*)stringArr;

/**
 *  返回名稱
 *
 *  @param stringArr 需要排序的字符數(shù)組
 *
 *  @return 更具首字母排序后的字符數(shù)組
 */
+ (NSMutableArray *)letterSortArray:(NSArray *)stringArr;

三. 將庫存數(shù)據(jù)按照索引分組排序

解決匹配首字母問題后, 則需要在所需控制器內(nèi)去解決分組排序問題了

// 庫存詳情列表數(shù)組
@property (nonatomic, strong) NSMutableArray *inventoryList;

// 索引標(biāo)題數(shù)組(排序后的出現(xiàn)過的拼音首字母數(shù)組)
@property(nonatomic, strong) NSMutableArray *indexArr;

// 排序好的結(jié)果數(shù)組
@property(nonatomic, strong) NSMutableArray *resultArr;
    // 根據(jù)YYPGoodsModel對象的 name 屬性 按中文 對 YYPGoodsModel數(shù)組 排序
    self.indexArr = [YYPChineseToPinyin indexWithArray:self.inventoryList Key:@"name"];
    self.resultArr = [YYPChineseToPinyin sortObjectArray:self.inventoryList Key:@"name"];

模擬加載庫存數(shù)據(jù):

- (void)loadInventoryData {
    NSArray *inventoryArr = [NSArray arrayWithObjects:
                              @"冰淇淋",@"土豆",@"##",
                              @"排骨",@"饅頭",@"老婆餅",
                              nil];
    
    self.inventoryList = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0; i < [inventoryArr count]; i++) {
        YYPGoodsModel *good = [[YYPGoodsModel alloc] init];
        good.name = [inventoryArr objectAtIndex:i];
        good.num = i * 100;
        good.cost = i + 100;
        [self.inventoryList addObject:good];
    }
}

四. 添加搜索功能

// 保存搜索狀態(tài)下的搜索數(shù)組
@property (strong, nonatomic) NSMutableArray *searchList;

添加手勢去移除鍵盤:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.searchBar resignFirstResponder];
}

- (void)tapAction{
    [self.tableView removeGestureRecognizer:_tap];
    [_searchBar resignFirstResponder];
}

使用代理UISearchBarDelegate做相應(yīng)操作:

#pragma mark - UISearchBarDelegate -

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    if (!_tap) {
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    }
    [self.tableView addGestureRecognizer:_tap];
    
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [self.searchList removeAllObjects];
    
    // 模擬加載搜索數(shù)據(jù)
    [self loadSearchData];
    
    self.showSearch = YES;
    [self.tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    if ([searchBar.text isEqualToString:@""]) {
        
        self.showSearch = NO;
        
        [self.tableView reloadData];
        
    } else {
        
        [self.searchList removeAllObjects];
        
        // 模擬加載搜索數(shù)據(jù)
        [self loadSearchData];
        
        self.showSearch = YES;
        [self.tableView reloadData];
    }
    
}

模擬加載搜索數(shù)據(jù):

- (void)loadSearchData {
    NSArray *searchArr = [NSArray arrayWithObjects:
                              @"排骨",@"饅頭",@"老婆餅",
                              nil];
    
    self.searchList = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0; i < [searchArr count]; i++) {
        YYPGoodsModel *search = [[YYPGoodsModel alloc] init];
        search.name = [searchArr objectAtIndex:i];
        search.num = i * 100;
        search.cost = i + 100;
        [self.searchList addObject:search];
    }
}

一般搜索來說是固定在頂部的,我這邊是用的UIViewController, 將搜索塊當(dāng)作子視圖放在內(nèi). 然后創(chuàng)建了myTableView去實(shí)現(xiàn)滾動這些頁面.


五. 搜索界面復(fù)用庫存界面, 增加標(biāo)識判斷顯示界面

由于我們搜索界面就是在當(dāng)前庫存頁面上搜索結(jié)果后直接展現(xiàn),并不存在跳轉(zhuǎn)下個界面,并且兩個界面的 cell 布局完全一樣. 這個時候只需要稍作處理復(fù)用即可(因?yàn)樗阉鞑淮嬖谒饕崾居浀萌サ羲饕齮itle).

定義一個是否標(biāo)識showSearch, 用于判斷是否顯示搜索結(jié)果

@property (assign, nonatomic) BOOL showSearch;

這個時候就修改上面的相關(guān)索引設(shè)置了, 增加判斷若是搜索狀態(tài)則不需要設(shè)置的邏輯:


#pragma mark - Table view data source

// 標(biāo)簽數(shù)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  
    if (self.showSearch) {
        return 1;
    }
    
    return self.indexArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.showSearch) {
        return self.searchList.count;
    }
    return [[self.resultArr objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YYPInventoryDetailsCell *cell =[YYPInventoryDetailsCell cellWithTableView:tableView];
    
    if (self.showSearch) {
        if (self.searchList.count) {
            YYPGoodsModel *model = self.searchList[indexPath.row];
            cell.model = model;
        }
        return cell;
    }
    
    YYPGoodsModel *model = [[self.resultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.model = model;
    return cell;
    
}
// 顯示每組標(biāo)題索引 (如果不實(shí)現(xiàn) 就不顯示右側(cè)索引)
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    
    if (self.showSearch) {
        return nil;
    }
    return self.indexArr;
}

// 設(shè)置索引section的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.showSearch) {
        return 0.0;
    }
    return 20;
}

// 返回每個索引的內(nèi)容
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (self.showSearch) {
        return @"";
    }
    
    return self.indexArr[section]; 
}

// 響應(yīng)點(diǎn)擊索引時的委托方法(點(diǎn)擊右側(cè)索引表項(xiàng)時調(diào)用)
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    
    return index;
}

如果需要修改分區(qū)header 索引的文字顏色及背景顏色, 和在tableview 里設(shè)置表頭一樣的修改方法.

// 設(shè)置索引背景顏色及標(biāo)題
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_View_Width, 20)];
    header.backgroundColor = YYPBackgroundColor;
   
    // Create label with section title
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(15, 0, UI_View_Width - 15, header.height);
    label.textColor = YYPColor(255, 255, 255);
    label.font = [UIFont systemFontOfSize:16.0];
    label.text = [[self.inventoryList objectAtIndex:section] valueForKey:@"name"];
    label.backgroundColor = [UIColor clearColor];
    [header addSubview:label];
    
    if (self.showSearch) {
        label.text = @"";
    } else {
        label.text = self.indexArr[section];
    }
    
    return header;
}

是不是思路很明了了,希望對大家有用!


索引排序搜索.gif

如果想看右側(cè)那種無索引條, 類似索引布局接口頁面請移步類似索引Model套Model之 iOS模型閑聊二

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市柳畔,隨后出現(xiàn)的幾起案子滋戳,更是在濱河造成了極大的恐慌痊土,老刑警劉巖信姓,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祝闻,死亡現(xiàn)場離奇詭異寄疏,居然都是意外死亡瞧栗,警方通過查閱死者的電腦和手機(jī)伴榔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門纹蝴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人踪少,你說我怎么就攤上這事塘安。” “怎么了援奢?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵兼犯,是天一觀的道長。 經(jīng)常有香客問我,道長切黔,這世上最難降的妖魔是什么砸脊? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮纬霞,結(jié)果婚禮上凌埂,老公的妹妹穿的比我還像新娘。我一直安慰自己诗芜,他們只是感情好瞳抓,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著伏恐,像睡著了一般孩哑。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上翠桦,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天横蜒,我揣著相機(jī)與錄音,去河邊找鬼秤掌。 笑死愁铺,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的闻鉴。 我是一名探鬼主播茵乱,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼孟岛!你這毒婦竟也來了瓶竭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤渠羞,失蹤者是張志新(化名)和其女友劉穎斤贰,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體次询,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡荧恍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了屯吊。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片送巡。...
    茶點(diǎn)故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖盒卸,靈堂內(nèi)的尸體忽然破棺而出骗爆,到底是詐尸還是另有隱情,我是刑警寧澤蔽介,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布摘投,位于F島的核電站煮寡,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏犀呼。R本人自食惡果不足惜幸撕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望圆凰。 院中可真熱鬧杈帐,春花似錦、人聲如沸专钉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽跃须。三九已至站叼,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間菇民,已是汗流浹背尽楔。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留第练,地道東北人阔馋。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像娇掏,于是被迫代替她去往敵國和親呕寝。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容