在UITableView或UIScrollView中添加管理单元位置 [英] Add snap-to position in a UITableView or UIScrollView

查看:101
本文介绍了在UITableView或UIScrollView中添加管理单元位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在UITableView或UIScrollView中添加捕捉位置?我的意思是,如果我按下按钮或调用某种方法来自动滚动到某个位置,我的意思是如果我滚动我的滚动视图或桌面视图围绕特定点,比如说 0,30 ,它会自动捕捉到它并留在那里?因此,如果我的滚动视图或表视图滚动,然后用户放入 0,25 0,35 之间,它将自动捕捉并滚动到那里?我可以想象可能会输入一个if语句来测试位置是否落在该区域的 scrollViewDidEndDragging:WillDecelerate: scrollViewWillBeginDecelerating: UIScrollView的方法,但我不确定如何在UITableView的情况下实现它。任何指导将不胜感激。

Is it possible to add a snap-to position in a UITableView or UIScrollView? What I mean is not auto scroll to a position if I press a button or call some method to do it, I mean is if I scroll my scroll view or tableview around a specific point, say 0, 30, it will auto-snap to it and stay there? So if my scroll view or table view scrolls and then the user lets go inbetween 0, 25 or 0, 35, it will auto "snap" and scroll there? I can imagine maybe putting in an if-statement to test if the position falls in that area in either the scrollViewDidEndDragging:WillDecelerate: or scrollViewWillBeginDecelerating: methods of UIScrollView but I'm unsure how to implement this in the case of a UITableView. Any guidance would be much appreciated.

推荐答案

就像Pavan所说,scrollViewWillEndDragging:withVelocity:targetContentOffset:是你应该使用的方法。它适用于表视图和滚动视图。如果您使用表格视图或垂直滚动​​滚动视图,下面的代码应该适合您。 44.0是示例代码中表格单元格的高度,因此您需要将该值调整为单元格的高度。如果用于水平滚动滚动视图,则将y替换为x,并将44.0更改为滚动视图中各个分区的宽度。

Like Pavan stated, scrollViewWillEndDragging: withVelocity: targetContentOffset: is the method you should use. It works with table views and scroll views. The code below should work for you if you are using a table view or vertically scrolling scroll view. 44.0 is the height of the table cells in the sample code so you will need to adjust that value to the height of your cells. If used for a horizontally scrolling scroll view, swap the y's for x's and change the 44.0 to the width of the individual divisions in the scroll view.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    // Determine which table cell the scrolling will stop on.
    CGFloat cellHeight = 44.0f;
    NSInteger cellIndex = floor(targetContentOffset->y / cellHeight);

    // Round to the next cell if the scrolling will stop over halfway to the next cell.
    if ((targetContentOffset->y - (floor(targetContentOffset->y / cellHeight) * cellHeight)) > cellHeight) {
        cellIndex++;
    }

    // Adjust stopping point to exact beginning of cell.
    targetContentOffset->y = cellIndex * cellHeight;
}

这篇关于在UITableView或UIScrollView中添加管理单元位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆