强制UITableView滚动到顶部?

时间:2012-06-29 21:22:19

标签: iphone objective-c ios uitableview

如果tableview包含少于10个左右的单元格,你会如何强制UITableViewCell滚动到顶部?我支持在tableview处于编辑模式时编辑tableView单元格中的托管对象上下文。不用说,如果一个单元格位于tableview的底部,当用户去编辑事件的标题或位置时,它会被键盘阻挡。我试过像这样的解决方案:

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

    if(_selectedIndex == indexPath.row){
        _selectedIndex = -1;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        return;
    }

    if(_selectedIndex >= 0){
        NSIndexPath *previous = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
        _selectedIndex = indexPath.row;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previous]
                         withRowAnimation:UITableViewRowAnimationFade];
    }

    _selectedIndex = indexPath.row;
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [tableView setContentOffset:CGPointMake(0, [tableView rowHeight]*indexPath.row) animated:YES];
}

但是这并没有将tableview保留在contentOffset上。它将捕捉到顶部,然后快照回来

8 个答案:

答案 0 :(得分:12)

我喜欢以下解决方案,因为如果你有一个,它也会滚动到标题视图的顶部。

[self.tableView setContentOffset:CGPointZero animated:YES];

答案 1 :(得分:4)

您可能应该在UITableView上使用此方法:

-(void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated

基本上你要做的是当你的UITableViewDelegate的[tableView:didSelectRowAtIndexPath:]方法被调用时,你将该选择的索引传递给上面的方法并设置scrollposition = UITableViewScrollPositionTop。

这会将所选单元格滚动到屏幕顶部,而不是键盘。

答案 2 :(得分:2)

您是否考虑过整个桌面视图?

编辑:我确实发现了一些看起来像你正在寻找的东西: Code here

此代码从底部缩小表格视图的插入,然后允许它显示其中一个较低的单元格,而不会向下捕捉。

答案 3 :(得分:2)

UITableView是UIScrollView的子类,因此您也可以使用:

[mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

答案 4 :(得分:1)

滚动到顶部tableView

会很有帮助
tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true).

答案 5 :(得分:0)

你试试这个吗? :

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;

样本是:

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

答案 6 :(得分:0)

这适用于我的情况,也可以滚动到headear的顶部如果你有:

  **myTablView.scrollRectToVisible((myTablView.rectForHeader(inSection: 0), to: myTablView.superview).0, animated: true)**

https://developer.apple.com/documentation/uikit/uitableview/1614872-rectforheader

答案 7 :(得分:0)

针对您的问题的更多指定答案:

captureTimeout
相关问题