之前寫過一篇純代碼實現UITableView的聯動效果的文章,查看地址:http://www.lxweimin.com/p/15625efdd146
接下來給大家介紹利用storyboard實現UITableView的聯動效果,分以下三部分進行介紹
界面搭建
創建新的XCode項目,在搭建如下圖所示的界面:一左一右兩個UITableView
界面搭建.png
運行結果
UITableView的聯動效果如下圖所示
運行結果圖.gif
代碼實現
1 主要實現方法
1.1 點擊cell的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
1.2 滾動右側UITableView的方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
2 具體代碼
//
// ViewController.m
// TwoTablesViewStroryboardDemo
//
// Created by Joyce on 16/11/23.
// Copyright ? 2016年 Joyce. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark ------------------
#pragma mark - 數據源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == _leftTableView) {
return 40;
}
return 8;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == _leftTableView) {
return 1;
}
return 40;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (tableView == _rightTableView) {
return [NSString stringWithFormat:@"第%ld組", section];
}
return nil;
}
#pragma mark ------------------
#pragma mark - 代理方法
// cell顯示
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] init];
if (tableView == _leftTableView) {
cell.backgroundColor = [UIColor cyanColor];
cell.textLabel.text = [NSString stringWithFormat:@"第%ld組", indexPath.row];
return cell;
} else if (tableView == _rightTableView) {
cell.backgroundColor = [UIColor purpleColor];
cell.textLabel.text = [NSString stringWithFormat:@"第%ld組,第%ld行", indexPath.section, indexPath.row];
return cell;
}
return nil;
}
// cell點擊
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == _leftTableView) {
[_rightTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row] animated:YES scrollPosition:UITableViewScrollPositionTop];
} else {
[_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
}
}
// 右側tableView的滾動
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == _rightTableView) {
[_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:[[_rightTableView indexPathsForVisibleRows] firstObject].section inSection:0] animated:YES scrollPosition:(UITableViewScrollPositionTop)];
}
}
@end
結束語
僅供學習參考,更多復雜功能還需小伙伴們親自動手實現,記得分享,互相學習??。