iOS tabview如何添加字母索引
本文实例为大家分享了iOStabview添加字母索引的具体代码,供大家参考,具体内容如下
文章转载自大神源码传送门
1、将汉字转换成首字母
//系统获取首字母
-(NSString*)pinyinFirstLetter:(NSString*)sourceString{
NSMutableString*source=[sourceStringmutableCopy];
CFStringTransform((__bridgeCFMutableStringRef)source,NULL,kCFStringTransformMandarinLatin,NO);
CFStringTransform((__bridgeCFMutableStringRef)source,NULL,kCFStringTransformStripDiacritics,NO);//这一行是去声调的
returnsource;
}
2、和tabview绑定的方法
#import"ViewController.h"
#import"BMChineseSort.h"
#import"Person.h"
@interfaceViewController(){
NSMutableArray*dataArray;
}
//排序后的出现过的拼音首字母数组
@property(nonatomic,strong)NSMutableArray*indexArray;
//排序好的结果数组
@property(nonatomic,strong)NSMutableArray*letterResultArr;
@end
@implementationViewController
-(void)viewDidLoad{
[superviewDidLoad];
//模拟数据加载dataArray中得到Person的数组
[selfloadData];
//BMChineseSort文件包含两个对单元格数据和右侧字母的数组排序函数
//根据Person对象的name属性按中文对Person数组排序
//每一个单元格的数据,排序好了的
self.indexArray=[BMChineseSortIndexWithArray:dataArrayKey:@"name"];
//左侧的字母数组,已经排序好了
self.letterResultArr=[BMChineseSortsortObjectArray:dataArrayKey:@"name"];
UITableView*table=[[UITableViewalloc]initWithFrame:self.view.frame];
table.delegate=self;
table.dataSource=self;
[self.viewaddSubview:table];
}
//加载模拟数据
-(void)loadData{
NSArray*stringsToSort=[NSArrayarrayWithObjects:
@"李白",@"张三",
@"重庆",@"重量",
@"调节",@"调用",
@"小白",@"小明",@"千珏",
@"黄家驹",@"鼠标",@"hello",@"多美丽",@"肯德基",@"##",
nil];
//模拟网络请求接收到的数组对象Person数组
dataArray=[[NSMutableArrayalloc]initWithCapacity:0];
for(inti=0;i<[stringsToSortcount];i++){
Person*p=[[Personalloc]init];
p.name=[stringsToSortobjectAtIndex:i];
p.number=i;
[dataArrayaddObject:p];
}
}
#pragmamark-UITableView-
//section的titleHeader
-(NSString*)tableView:(UITableView*)tableViewtitleForHeaderInSection:(NSInteger)section{
return[self.indexArrayobjectAtIndex:section];
}
//section行数
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{
return[self.indexArraycount];
}
//每组section个数
-(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{
return[[self.letterResultArrobjectAtIndex:section]count];
}
//section右侧index数组
-(NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView{
returnself.indexArray;
}
//点击右侧索引表项时调用索引与section的对应关系
-(NSInteger)tableView:(UITableView*)tableViewsectionForSectionIndexTitle:(NSString*)titleatIndex:(NSInteger)index{
returnindex;
}
//返回cell
-(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{
UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:@"CELL"];
if(cell==nil){
cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@"CELL"];
}
//获得对应的Person对象<替换为你自己的model对象>
Person*p=[[self.letterResultArrobjectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
cell.textLabel.text=p.name;
returncell;
}
@end
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。