I have a scrollView (width:320px height:100px) on my UIView, inside it I add 10 images with width:106.5px each. After that I use this function to have 3 different parts inside my scrollView, so everytime I scroll, an image will automatically be center.
-(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];
}
Here is my question, I want to be able to know which image will be in the middle position after the user scroll the View, because I want to display on my UIView a text, specific to that image. But I don’t know how to do that.
Some Ideas?
Well, I am not going to paste in a lot of code here, but this is how I do that:
I keep a spatial index (rtree) where I insert all my objects. It is much faster to obtain list of items intersecting with a given one.
I have a class that is also my scrollview’s delegate. And every time scrollViewDidScroll: gets called I obtain visibleRect of the my content view, then using rtree index quickly locate items that are in the rect, and draw accordingly.
You would only have to decide which image is “in the middle” in case yours are small, and there might be 4 fitting in the visible rectangle of the scroll view.
Hope that helps,
Robert