iOS小技能: tableView滚到指定位置(视图的最顶部或者最底部)

2,603 阅读2分钟

这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战

粉丝福利:搜索#小程序:iOS逆向 ,关注公众号:iOS逆向领取福利【掘金小册5折优惠码】

(有效日期至 11月30日 23:59)

前言

粉丝福利:搜索#小程序:iOS逆向 ,关注公众号:iOS逆向领取福利【掘金小册5折优惠码】 (有效日期至 11月30日 23:59)

需求: 显示一个 top 的按钮 ,点top返回到顶部

应用场景1: 界面内容比较多的时候,需要一个返回到顶部的开关

例子:商户信息变更时在基基本信息页显示一个 top 的按钮 ,点top返回到顶部

应用场景2·:当一个界面的数据更新之后,我们希望回到顶部的时候就可以使用这个方法。

例子: 当计算表达式发生变化时,需要将收银台界面的计算器界面回到最顶部进行显示最新的计算结果

I、iOS tableView滚到最顶部的方案

1.1 scrollToRowAtIndexPath

本人比较喜欢采用``scrollToRowAtIndexPath,因为它不仅可以滚动到最顶部,还支持到特定位置。

点top返回到顶部

                        [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                       

滚动到指定位置

            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:QCTChangeBasicViewSection4businessLicenseInforow4Last inSection:QCTChangeBasicViewSection4businessLicenseInfo] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

1.2 setContentOffset

  • setContentOffset
                        [weakSelf.tableView setContentOffset:CGPointMake(0,0) animated:NO];
                        

1.3 scrollRectToVisible

  • scrollRectToVisible
            [self.vcView.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

1.4 scrollsToTop

        [weakSelf.tableView scrollsToTop];

UIScrollViewDelegate 的scrollViewShouldScrollToTop 方法必须返回YES 在这里插入图片描述

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView;   // return a yes if you want to scroll to the top. if not defined, assumes YES

II scrollToRowAtIndexPath实现特定需求

使用scrollToRowAtIndexPath来解决更新reloadData的带来的界面跳动

更新公告分组数据时就可以使用以下方式来解决

    [self.viewModel.reloadSubject4Note subscribeNext:^(id  _Nullable x) {
        
        
        if(self.viewModel.isShow_msg){
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:QCTStoreViewSection4msg] atScrollPosition:UITableViewScrollPositionTop animated:YES];


        }else{
            
            
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:QCTStoreViewSection4Banner] atScrollPosition:UITableViewScrollPositionTop animated:YES];


//        :
        }
        
        [weakSelf.tableView reloadData];

        

        
        
    }];

see also

更多内容请关注#小程序:iOS逆向,只为你呈现有价值的信息,专注于移动端技术研究领域。