关于iOS

仿美团外卖tableview联动

2016-09-28  本文已影响404人  安然slience

tableview是我们开发中用的最多的控件,很多商城,外卖软件都用到了tableview联动的功能,今天就整理了一下,给自己记录一下,也给不会的同学看一下,不喜勿喷,谢谢!

tableview要联动的话,首先要有两个tableview,我先贴上tableview的一些主要代码,下面会附上github地址,供大家参考.

tableviewDatasource:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.leftTableView) {
        return 1;
    }else {
        return 50;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.leftTableView) {
        return 50;
    }else {
        return 10;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (tableView == self.leftTableView) {
        cell = [tableView dequeueReusableCellWithIdentifier:leftTableViewCell forIndexPath:indexPath];
        cell.textLabel.text = [NSString stringWithFormat:@"%ld组",indexPath.row];
    }else {
        cell = [tableView dequeueReusableCellWithIdentifier:rightTableViewCell forIndexPath:indexPath];
        cell.textLabel.text = [NSString stringWithFormat:@"第%ld组--第%ld行",indexPath.section,indexPath.row];
    }

    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView == self.rightTableView) {
        return [NSString stringWithFormat:@"第%ld组",section];
    }
    return nil;
}

tableviewDelegate:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (tableView == self.leftTableView) {//点击左侧的tableview,右边的tableview跟着滑动到相应位置
        NSIndexPath *moveToIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
    
//      [self.rightTableView selectRowAtIndexPath:moveToIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    [self.rightTableView scrollToRowAtIndexPath:moveToIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.leftTableView) return;
        //取出出现在右边tableview上的最上方的cell的indexPath

        NSIndexPath *topIndexPath = [[self.rightTableView indexPathsForVisibleRows] firstObject];

        //计算左侧tableview移动的indexPath

        NSIndexPath *moveToIndexPath = [NSIndexPath indexPathForRow:topIndexPath.section inSection:0];
  
        [self.leftTableView selectRowAtIndexPath:moveToIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}

以上是主要代码,下面附上github地址:https://github.com/ZSyingyu/TestDemo.git

仅供参考!

上一篇 下一篇

猜你喜欢

热点阅读