在UIScrollView中滚动后对象的位置

时间:2010-04-23 02:34:09

标签: iphone objective-c uiscrollview

我的UIView上有一个scrollView(宽度:320px高度:100px),在其中我添加了10个宽度为106.5px的图像。之后我使用这个函数在我的scrollView中有3个不同的部分,所以每次滚动时,图像都会自动居中。


-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    [self returnToPosition:self.scrollView];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    [self returnToPosition:self.scrollView];
}

-(void)returnToPosition:(UIScrollView *)scrollView {

    CGFloat itemWidth = 106.5f;
    CGFloat position = [self.scrollView contentOffset].x;
    CGFloat newPosition = 0.0f;
    CGFloat offSet = position / itemWidth;
    NSUInteger target = (NSUInteger)(offSet + 0.5f);

    newPosition = target * itemWidth;

    [self.scrollView setContentOffset:CGPointMake(newPosition, 0.0f) animated:YES];

}

这是我的问题,我希望能够在用户滚动视图后知道哪个图像将处于中间位置,因为我想在我的UIView上显示特定于该图像的文本。但我不知道该怎么做。

一些想法?

1 个答案:

答案 0 :(得分:0)

好吧,我不会在这里粘贴很多代码,但这就是我这样做的方式: 我保留了一个空间索引(rtree),我插入了所有对象。获得与给定项目相交的项目列表要快得多。 我有一个类也是我的scrollview的委托。每次调用scrollViewDidScroll:我都会获取my内容视图的visibleRect,然后使用rtree index快速定位rect中的项目,并相应地绘制。

你只需决定哪个图像是“在中间”,以防你的图像很小,并且在滚动视图的可见矩形中可能有4个拟合。

希望有所帮助, 罗伯特