scrollToRowAtIndexPath 问题分析(crash 和 不执行问题)

本文介绍了UITableView在使用scrollToRowAtIndexPath时可能发生的崩溃原因及解决办法,并提供了如何正确设置tableView的frame来避免滚动问题的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、scrollToRowAtIndexPath 会发生崩溃:

//scroll to previously selected cell
  [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.lastIdx inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

崩溃的原因是:

比如数据源中有3个元素,而tableview中只显示了2个元素,当调用scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:2
时肯定就出错了。


解决方法是: 在调用这个方法之前刷新数据源

[self.tableView reloadData];

二、不执行或者执行错误的问题:


背景:在用纯代码(purelauout布局的情况下),给tableView设置了约束,但是没有给frame

- (void)initializeTableView
{
    self.view.backgroundColor = HEXCOLOR(0xf0f0f0);
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = HEXCOLOR(0xf0f0f0);
    [self.view addSubview:self.tableView];
    
    [self.tableView tn_pinEdgeToSuperviewEdge:TNAEdgeLeading withInset:0.0f];
    [self.tableView tn_pinEdgeToSuperviewEdge:TNAEdgeTop withInset:self.topBarView.height];
    [self.tableView tn_matchDimension:TNADimensionWidth toDimension:TNADimensionWidth ofView:self.view];
    [self.tableView tn_pinEdgeToSuperviewEdge:TNAEdgeBottom withInset:0.0f];
}


在执行scrollToRowAtIndexPath 是不知道tableView的frame的,所有滚冬到相对应的cell就有问题。


给定tableView的frame:

self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

就可以。

其次,防止crash,可以设置代码保护:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //protect code
    if ([self tableView:self.tableView numberOfRowsInSection:[NSIndexPath indexPathForRow:self.lastIdx inSection:0].section] > [NSIndexPath indexPathForRow:self.lastIdx inSection:0].row) {
        if (self.lastIdx != NSNotFound && self.lastIdx < self.holder.customers.count) {
            //scroll to previously selected cell
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.lastIdx inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
            self.lastIdx = NSNotFound;
        }
    }
}
因为业务本身只有一组,所以我没有设置组的判断,可以的话设置上,注意要实现tableView的组方法,否则会报 unresgonized selector !!!




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值