如何使用滚动动画关注UITableview中的最后一个单元格?

时间:2013-02-07 04:06:17

标签: ios objective-c cocoa-touch uitableview

我的xcode项目中有一个UITableview。列出了注释。如何通过滚动动画关注我的TableView的最后一个单元格?

3 个答案:

答案 0 :(得分:26)

下面的方法将找到您的表格视图的最后一个索引,并将重点关注具有动画的该单元格

-(void)goToBottom
{
    NSIndexPath *lastIndexPath = [self lastIndexPath];

    [<YOUR TABLE VIEW> scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

查找tableview的最后一个索引的代码。

-(NSIndexPath *)lastIndexPath
{
    NSInteger lastSectionIndex = MAX(0, [<YOUR TABLE VIEW> numberOfSections] - 1);
    NSInteger lastRowIndex = MAX(0, [<YOUR TABLE VIEW> numberOfRowsInSection:lastSectionIndex] - 1);
    return [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
}

在视图控制器中的某处添加此代码

[self performSelector:@selector(goToBottom) withObject:nil afterDelay:1.0];

答案 1 :(得分:2)

请记住,UITableView继承自UIScrollView

-(void)scrollToBottom:(id)sender
{
    CGSize r = self.tableView.contentSize;
    [self.tableView scrollRectToVisible:CGRectMake(0, r.height-10, r.width, 10) animated:YES];
}

一样执行它
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(…);
[button addTarget:self action:@selector(scrollToBottom:) forControlEvents:UIControlEventTouchUpInside];

(您不需要使用performSelector:…


另一种解决方案是选择最后一行。表格视图将处理其余部分。

-(void)scrollToBottom:(id)sender
{
    NSInteger lasSection = [self.tableView numberOfSections] - 1;
    NSInteger lastRow = [self.tableView numberOfRowsInSection:lasSection]-1;

    //this while loops searches for the last section that has more than 0 rows.
    // maybe you dont need this check
    while (lastRow < 0 && lasSection > 0) {
        --lasSection;
        lastRow = [self.tableView numberOfRowsInSection:lasSection]-1;
    }
    //if there is no section with any row. if your data source is sane,
    // this is not needed.
    if (lasSection < 0 && lastRow < 0)
        return;

    NSIndexPath *lastRowIndexPath =[NSIndexPath indexPathForRow:lastRow inSection:lasSection];
    [self.tableView selectRowAtIndexPath:lastRowIndexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
}

按钮是一样的。

答案 2 :(得分:0)

斯威夫特3:

let indexPath = IndexPath(row: /*ROW TO SCROLL TO*/, section: /*SECTION TO SCROLL TO*/)
tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)