在VC.m里面写:
#import “ViewController.h”
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView * tableView;
@property(nonatomic,strong) NSMutableArray * dataSource;//数据源
@property(nonatomic,strong) NSMutableArray * indexArray;//索引数组
@property(nonatomic,strong) NSArray * AllArray;//混乱的数据
@property(nonatomic,strong) NSMutableDictionary * dicData;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
_AllArray = @[@“范梦豪”,@“赵硕琦”,@“赵仁和”,@“岳社通”,@“刘瑞”,@“郭星佐”,@“陈威宇”,@“王晓宇”,@“索振杰”,@“张海”];
_dicData = [[NSMutableDictionary alloc]init];
//按名称首字母分类数据
[self initData];
[self.view addSubview:self.tableView];
}
-(void)initData{for (NSString * name in _AllArray) {
NSMutableString * str = [[NSMutableString alloc]initWithString:name]; //文字转拼音 CFStringTransform((CFMutableStringRef)str, 0, kCFStringTransformToLatin, NO); NSLog(@"-----------------------------------%@",str); //获取字符 char c = [str characterAtIndex:0]; NSLog(@"***********************************%c",c); //字符转字符串 NSString * s = [NSString stringWithFormat:@"%c",c]; NSLog(@"#####################################%@",s); //以索引字母获取字典中的数组 NSMutableArray *nameArr = [self.dicData objectForKey:s]; if (nameArr.count == 0) { //如果取出的是空的,说明字典中没有这个key对应的值,就创建一个 nameArr = [NSMutableArray array]; //将创建的数组赋值给字典 [self.dicData setObject:nameArr forKey:s]; } //将名字加到数组 [nameArr addObject:name]; //索引数据: _indexArray = [NSMutableArray arrayWithArray:[self.dicData allKeys]]; //排序: [_indexArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [obj1 compare:obj2]; }];
}
}
-(UITableView *)tableView{
if (!_tableView) {
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
_tableView.delegate = self;
_tableView.dataSource = self;
}
return _tableView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return self.indexArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *arr = [self.dicData objectForKey:[_indexArray objectAtIndex:section]];
return arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@“cell”];
if (cell==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@“cell”];
}
NSArray *arr = [self.dicData objectForKey:[_indexArray objectAtIndex:indexPath.section]];
cell.textLabel.text = [arr objectAtIndex:indexPath.row];
return cell;
}
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{return self.indexArray;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return self.indexArray[section];
}
效果图: