设置宏定义
// 获取整个屏幕的宽度,高度
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
设置 TableView 和 ScrollView 的协议
<UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate>
// 定义成员变量
{
UITableView *leftTableView; // 左边的表格
UITableView *rightTableView; // 右边的表格
NSArray *titArr; // 标题数组 (左边的标题和右边的分区标题相对应是同一个数组)
}
在 viewDidLoad 中创建表格和数组
- (void)viewDidLoad {
[super viewDidLoad];
// 创建表格
// 左侧的表格 -- 是不分区的表格
leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 0.3, HEIGHT) style:UITableViewStylePlain];
leftTableView.delegate = self;
leftTableView.dataSource = self;
[self.view addSubview:leftTableView];
// 右侧的表格 -- 是一个分区的表格
rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH * 0.3, 0, WIDTH * 0.7, HEIGHT) style:UITableViewStyleGrouped];
rightTableView.delegate = self;
rightTableView.dataSource = self;
[self.view addSubview:rightTableView];
// 标题数组
titArr = @[@"1",@"2",@"3",@"4",@"5"];
}
// 设置表格分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView == rightTableView) {
// 右侧表格的分区数为定义的 arr 的数量
return titArr.count;
}else{
return 1;
}
}
// 设置行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == leftTableView) {
// 左侧的表格的行数就是标题数组的个数
return titArr.count;
}else{
// 右侧表格的每个分区内的行数
return 10;
}
}
// 设置内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
if (tableView == leftTableView) {
// 左侧表格的内容就是标题数组中的内容
cell.textLabel.text = titArr[indexPath.row];
}else{
// 右侧表格的内容
cell.textLabel.text = @"yly";
}
return cell;
}
// 设置右侧表格的分区的标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (tableView == rightTableView) {
// 设置右侧表格的分区的标题
return titArr[section];
}else{
return nil;
}
}
// 点击左侧单元格,将右侧表格移动到指定位置
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == leftTableView) {
NSIndexPath *moveToPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
[rightTableView selectRowAtIndexPath:moveToPath animated:YES scrollPosition:UITableViewScrollPositionTop];
}
}
// 滚动右侧表格,左侧联动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (scrollView == rightTableView) {
NSIndexPath *topPath = [[rightTableView indexPathsForVisibleRows] firstObject];
NSIndexPath *moveIndex = [NSIndexPath indexPathForRow:topPath.section inSection:0];
[leftTableView selectRowAtIndexPath:moveIndex animated:YES scrollPosition:UITableViewScrollPositionTop];
}
}