UITableView实现通讯录效果
//
// TableViewIndexViewController.m
// study2024
//
// Created by figo zhu on 2024/12/22.
//#import "TableViewIndexViewController.h"
//实现协议UITableViewDelegate,UITableViewDataSource
@interface TableViewIndexViewController ()<UITableViewDelegate,UITableViewDataSource>
//通讯录索引tableview
@property (weak, nonatomic) IBOutlet UITableView *indexTableView;
//通讯录组
@property (strong,nonatomic) NSArray *sectionGroup;
//通讯录所有名字
@property (strong,nonatomic) NSArray<NSArray *> *sectionNames;@end@implementation TableViewIndexViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view from its nib.//数据源设置为自己self.indexTableView.dataSource=self;//代理设置为自己self.indexTableView.delegate=self;//获取屏幕大小int screenWidth = UIScreen.mainScreen.bounds.size.width;int screenHeight = UIScreen.mainScreen.bounds.size.height;int x = UIScreen.mainScreen.bounds.origin.x;int y = UIScreen.mainScreen.bounds.origin.x;//设置tableview的左上角坐标,及宽和高[self.indexTableView setFrame:CGRectMake(x, y, screenWidth, screenHeight)];//通讯录组self.sectionGroup=[[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",nil];//通讯录名称self.sectionNames=[[NSArray alloc] initWithObjects:@[@"阿猫",@"阿狗"], @[@"步青云",@"步步高"],@[@"曹操",@"陈陈"],@[@"当当",@"弟弟"],@[@"艺龙",@"依依"],@[@"芳芳",@"福临"],@[@"高一",@"高二",@"高三"],@[@"黄帝",@"黄蓉"],nil];//设置索引颜色self.indexTableView.sectionIndexColor=[UIColor blueColor];//设置索引背景颜色self.indexTableView.sectionIndexBackgroundColor=[UIColor greenColor];}/*
#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {// Get the new view controller using [segue destinationViewController].// Pass the selected object to the new view controller.
}
*/
//每行的数据展示
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {UITableViewCell *cell=[self.indexTableView dequeueReusableCellWithIdentifier:@"abc"];if(cell==nil){cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"abc"];}cell.textLabel.text=self.sectionNames[indexPath.section][indexPath.row];return cell;
}
//每一段的行数
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return self.sectionNames[section].count;
}
//总共有几段
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return self.sectionGroup.count;
}
//每一段的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{return self.sectionGroup[section];
}
//返回分组标题数组
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{return self.sectionGroup;
}
//获取点击的索引标题
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{NSLog(@"你点击的索引是%@",title);return index;
}
@end
效果: