設置宏定義
// 獲取整個屏幕的寬度,高度
#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];
}
}