iOS tableView的点击联动效果

效果是这样子的:如下图
1

668737-ccd3e667e4c0d6bc.png
639F260E-22C5-44CB-BA80-E17EF395BFAC.png

导航栏上有两个按钮 点击时切换当前界面,当前的界面其实是一个tableview的cell,点击下一页或者上一页的时候tableview会上下翻页,就是这么个效果。
2

668737-1fb824c5898fd7e5.png
E8F76E55-A832-4D86-AE54-5BBF66DCC594.png

当翻到最后一页或者第一页时,按钮不可用

下面是主要的代码:

声明全局变量  NSInteger _currentIndex;//当前的索引值

tableview的上下翻页效果:_tableView.pagingEnabled = YES; 为了美观去掉竖直方向滚动的滑条:_tableView.showsVerticalScrollIndicator = NO;

处理点击事件:
#pragma mark - 按钮点击事件
- (void)frontClick {
    /**< 上一条消息 */
    _nextBtn.enabled = YES;
    _currentIndex--;     //判断有没有上一条
    NSLog(@"currentIndex:%ld", (long)_currentIndex);
    if (_currentIndex >=  0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    } else {
        _currentIndex = 0;
        _frontBtn.enabled = NO;
    }
    
}

- (void)nextClick {
    /**< 下一条消息 */
    _frontBtn.enabled = YES;
    _currentIndex ++;       //判断有没有下一条
    NSLog(@"currentIndex:%ld", (long)_currentIndex);
    if (_currentIndex< _arr.count) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }    else {
        _nextBtn.enabled = NO;
        _currentIndex = _arr.count - 1;
    }
    
}

小结:其实主要的就是
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

通过_currentIndex 找到当前的索引,然后让tableview滚动到指定的索引行数。
还有一点小逻辑的操作,就是点击按钮时的_currentIndex的变化。首先_currentIndex默认为0,那么当开始点击上一条的时候,此时用_currentIndex-- 判断当前的索引有没有上一条,如果_currentIndex >= 0的话就让tableview向指定的索引滚动。如果<0 了 就让_currentIndex = 0;使按钮失效。然后当点击下一条按钮的时候,让_currentIndex ++ 判断当前所以是不是超出了数组中的元素的索引,如果没有就滚动。如果超出了 就让_currentIndex为数组里元素的最后的索引值。让按钮失效。大体就这样子。

代码gitHub地址:https://github.com/irembeu/TableViewRepository.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值