IOS实现左右两个TableView联动效果

2020-01-15 18:01:49丽君

一、先来看看要实现的效果图

两个tableview联动,ios,tableview,联动,tableview左右联动

二、小解析,可以先看看后面的!

两个tableview联动,ios,tableview,联动,tableview左右联动

三、实现 tableView联动 主要分两种状况

     1、点击 左侧 cell 让右侧 tableView 滚到对应位置

     2、滑动 右侧 tableView 让左侧 tableView 滚到对应位置

1.先实现简单的:点击 左侧 cell 让右侧 tableView 滚到对应位置


//MARK: - 点击 cell 的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

 // 判断是否为 左侧 的 tableView
 if (tableView == self.leftTableView) {

  // 计算出 右侧 tableView 将要 滚动的 位置
  NSIndexPath *moveToIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];

  // 将右侧 tableView 移动到指定位置
  [self.rightTableView selectRowAtIndexPath:moveToIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];

  // 取消选中效果
  [self.rightTableView deselectRowAtIndexPath:moveToIndexPath animated:YES];
 }
}

左侧 按钮点击的联动 搞定!

2.滑动 右侧 tableView 让左侧 tableView 滚到对应位置

[self.rightTableView indexPathsForVisibleRows] 返回 所有显示在界面的 cell 的 indexPath


//MARK: - 一个方法就能搞定 右边滑动时跟左边的联动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

 // 如果是 左侧的 tableView 直接return
 if (scrollView == self.leftTableView) return;

 // 取出显示在 视图 且最靠上 的 cell 的 indexPath
 NSIndexPath *topHeaderViewIndexpath = [[self.rightTableView indexPathsForVisibleRows] firstObject];

 // 左侧 talbelView 移动到的位置 indexPath
 NSIndexPath *moveToIndexpath = [NSIndexPath indexPathForRow:topHeaderViewIndexpath.section inSection:0];

 // 移动 左侧 tableView 到 指定 indexPath 居中显示
 [self.leftTableView selectRowAtIndexPath:moveToIndexpath animated:YES scrollPosition:UITableViewScrollPositionMiddle];

}

第二步 右侧 滑动 跟左侧 的联动 搞定! 对的 就是这么简单!!!

四、警告

看到别人通过这两个方法判断!!! 勿用!!!

会导致 tableView 的联动 不准确


#pragma mark - UITableViewDelegate 代理方法 -
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
//
// headerView 将要显示
// 这两个方法都不准确
}
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
//
// headerView 已经显示
// 这两个方法都不准确
}