實現按照字母分類分組排序

這裏寫圖片描述
爲了實現上圖字母分類排序
實現過程借鑑了網上 大神的博客筆記
http://www.cnblogs.com/fxiaoquan/p/4724208.html
實現過程如下:
下載 pinyin.c 和 pinyin.h 文件 導入到項目中
這裏寫圖片描述
這裏創建一個處理對象的數據模型
這裏寫圖片描述
將大神的代碼copy到模型中 替換成自己想要的數據模型

//
//  ChineseString.h
//  SAGA_iOS
//
//  Created by  location on 16/8/10.
//  Copyright © 2016年 it.sozi. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "PinYin.h"
#import "CZHomeSearchBrandItem.h"

@interface ChineseString : NSObject

@property(nonatomic,copy) NSString *string;
@property(nonatomic,copy) NSString *pinYin;
@property(nonatomic,strong)CZHomeSearchBrandItem *brandItem;


/**
 *  TableView右方IndexArray
 */
+(NSMutableArray *) IndexArray:(NSArray *) stringArr;

/**
 *  文本列表
 */
+(NSMutableArray *) LetterSortArray:(NSArray *)stringArr;

/**
 *返回一組字母排列數組(中英混排)
 */
+(NSMutableArray *) SortArray:(NSArray *)stringArr;

實現文件

//
//  ChineseString.m
//  SAGA_iOS
//
//  Created by  location on 16/8/10.
//  Copyright © 2016年 it.sozi. All rights reserved.
//

#import "ChineseString.h"

@implementation ChineseString

- ( id )init {

    if ( self = [ super init ]) {



    }



    return self ;

}

#pragma mark - 返回tableview右方 indexArray
+(NSMutableArray*)IndexArray:(NSArray*)stringArr
{
    NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
    NSMutableArray *A_Result=[NSMutableArray array];
    NSString *tempString ;

    for (NSString* object in tempArray)
    {
        NSString *pinyin = [((ChineseString*)object).pinYin substringToIndex:1];
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            [A_Result addObject:pinyin];
            tempString = pinyin;
        }
    }
    return A_Result;
}

#pragma mark -
+(NSMutableArray*)LetterSortArray:(NSArray*)stringArr
{
    NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
    NSMutableArray *LetterResult=[NSMutableArray array];
    NSMutableArray *item = [NSMutableArray array];
    NSString *tempString;
    //拼音分組
    for (NSObject* object in tempArray) {
        NSString *pinyin = [((ChineseString*)object).pinYin substringToIndex:1];
        CZHomeSearchBrandItem *brandItem=((ChineseString*)object).brandItem;
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            //分組
            item = [NSMutableArray array];
            [item  addObject:brandItem];
            [LetterResult addObject:item];
            //遍歷
            tempString = pinyin;
        }else//相同
        {
            [item  addObject:brandItem];
        }
    }
    return LetterResult;
}

/**
 * 過濾指定字符串   裏面的指定字符根據自己的需要添加
 */
+(NSString*)RemoveSpecialCharacter: (NSString *)str {
    NSRange urgentRange = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @",.?、 ~¥#&<>《》()[]{}【】^@/£¤|§¨「」『』¢¬ ̄~@#&*()——+|《》$_€"]];
    if (urgentRange.location != NSNotFound)
    {
        return [self RemoveSpecialCharacter:[str stringByReplacingCharactersInRange:urgentRange withString:@""]];
    }
    return str;
}

/**
 *  返回排序好的字符拼音
 *
 */
+(NSMutableArray*)ReturnSortChineseArrar:(NSArray*)stringArr
{
    //獲取字符串中文字的拼音首字母並與字符串共同存放
    NSMutableArray *chineseStringsArray=[NSMutableArray array];
    for(int i=0;i<[stringArr count];i++)
    {
        ChineseString *chineseString=[[ChineseString alloc]init];
        CZHomeSearchBrandItem *brandItem=[stringArr objectAtIndex:i];
        chineseString.brandItem=brandItem;
        chineseString.string=[NSString stringWithString:brandItem.name];
        if(chineseString.string==nil){
            chineseString.string=@"";
        }
        //去除兩端空格和回車
        chineseString.string  = [chineseString.string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        //此方法存在一些問題 有些字符過濾不了
        //NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];
        //chineseString.string = [chineseString.string stringByTrimmingCharactersInSet:set];

        //這裏我自己寫了一個遞歸過濾指定字符串   RemoveSpecialCharacter
        chineseString.string =[ChineseString RemoveSpecialCharacter:chineseString.string];
        // NSLog(@"string====%@",chineseString.string);

        //判斷首字符是否爲字母
        NSString *regex = @"[A-Za-z]+";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        NSString *initialStr = [chineseString.string length]?[chineseString.string substringToIndex:1]:@"";
        if ([predicate evaluateWithObject:initialStr])
        {
            NSLog(@"chineseString.string== %@",chineseString.string);
            //首字母大寫
            chineseString.pinYin = [chineseString.string capitalizedString] ;
        }else{
            if(![chineseString.string isEqualToString:@""]){
                NSString *pinYinResult=[NSString string];
                for(int j=0;j<chineseString.string.length;j++){
                    NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",
                                                   pinyinFirstLetter([chineseString.string characterAtIndex:j])]uppercaseString];
                    pinYinResult=[pinYinResult stringByAppendingString:singlePinyinLetter];
                }
                chineseString.pinYin=pinYinResult;
            }else{
                chineseString.pinYin=@"";
            }
        }
        [chineseStringsArray addObject:chineseString];
    }
    //按照拼音首字母對這些Strings進行排序
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinYin" ascending:YES]];
    [chineseStringsArray sortUsingDescriptors:sortDescriptors];
    return chineseStringsArray;

}

#pragma mark - 返回一組字母排序數組
+(NSMutableArray*)SortArray:(NSArray*)stringArr
{
    NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];

    //把排序好的內容從ChineseString類中提取出來
    NSMutableArray *result=[NSMutableArray array];
    for(int i=0;i<[stringArr count];i++){
        [result addObject:((ChineseString*)[tempArray objectAtIndex:i]).string];
    }
    return result;
}

在獲取數據的控制器頁面導入#import “ChineseString.h”
@property(nonatomic,strong)NSMutableArray *indexArray;//去重後的首字母
@property(nonatomic,strong)NSMutableArray *letterResultArr;//按照首字母排序後的集合
初始化兩個數組來接收排序後的數據
實現相應的類方法

-(void)setWatchBrands:(NSArray *)watchBrands
{
    _watchBrands = watchBrands;
    if (watchBrands) {
        //返回tableview右方 indexArray
        self.indexArray = [ChineseString IndexArray:watchBrands];
        self.letterResultArr = [ChineseString LetterSortArray:watchBrands];
    }

    [self.tableView reloadData];
}

以上就已經將後臺返回的數據 進行字母編排 編排後賦值給相應的數組 tableView 實現對應的數據源 和代理方法

//多少組
- (NSInteger)numberOfSectionsInTableView:( UITableView *)tableView
{

    return self.indexArray.count;

}

//每組中有多少行
- (NSInteger)tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section
{

    return [[self.letterResultArr objectAtIndex:section]count];

}

// 爲 section 添加標題
- (NSString *)tableView:( UITableView *)tableView titleForHeaderInSection:( NSInteger )section
{

    return [self.indexArray objectAtIndex :section];

}

//tableView 右邊顯示的字母
- (NSArray *)sectionIndexTitlesForTableView:( UITableView *)tableView
{

    return self.indexArray;

}



#pragma mark - Table view data source

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *brandID =@"brandID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:brandID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:brandID];
    }
    CZHomeSearchBrandItem *brandItem = [[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    cell.textLabel.text = brandItem.name;
    cell.textLabel.font = CZFontMiddle;
    cell.textLabel.textColor = CZColor(@"#333333");
    return cell;
}

展示效果如上圖
非常感謝大神的代碼 讓我實現了字母分類分組排序
詳細實現可參照 此鏈接 http://www.cnblogs.com/fxiaoquan/p/4724208.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章