0

I have a UIScrollView which is horizontale scrollable. Inside this view I have added some views as subviews. How can I detect which view is in the middle of the screen and is selected by the user?

I thought of something like didSelectRowAtIndexPath: just for a scroll view.

Thanks

rmaddy
  • 314,917
  • 42
  • 532
  • 579
David P
  • 228
  • 2
  • 14
  • No there isn't. But there is a delegate method `scrollViewDidScroll`, and different `contentOffset` & `contentSize` property, you can know what is showed. – Larme Apr 14 '14 at 13:05
  • Ah okay, I understand. Could you show me how to detect which view is selected? – David P Apr 14 '14 at 13:07

3 Answers3

0

you can check contentOffSet property of UIScrollView and then check for the view at that CGPoint in scrollView. you can refer this link which shows how to get UIView from CGPoint.

Community
  • 1
  • 1
2intor
  • 1,044
  • 1
  • 8
  • 19
0

You can catch touches like this (from your UIScrollView subclass):

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches) {
        CGPoint locationInScroll = [touch locationInView:scrollView];
        for (UIView *view in scrollView.subviews) {
            if (CGRectContainsPoint(view.frame, locationInScroll)) {
                // that's it
                break;
            }
        }
    }
}

Or you can try to use UITapGestureRecognizer in a similar way.

kpower
  • 3,871
  • 4
  • 42
  • 62
  • Is there a way do to this within the `scrollViewDidEndDecelerating:scrollView:`method? – David P Apr 14 '14 at 13:32
  • You can get `scrollView.contentOffset` to get coordinates of top-left visible point and `scrollView.contentSize` to get visible size. But how do you expect user to "select" a view without tapping? – kpower Apr 14 '14 at 15:30
0

In the touchesEnded or gesture recognizer function, get the exact point within the scroll view where the click is made.

CGPoint touchPoint=[gesture locationInView:scrollView];

Then divide the y value of the touchPoint with the height of each view to get the exact UIView within the scrollView

int point = (touchPoint.y) / heightOfSingleView; 

Then get this particular view within the scrollview as follows:

UIView* view=[[locationInView:scrollView subviews] objectAtIndex:point];

Exact code would look like this:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 CGPoint touchPoint=[gesture locationInView:scrollView];
 int point = (touchPoint.y) / heightOfSingleView;
 UIView* view=[[locationInView:scrollView subviews] objectAtIndex:point];
}
Khawar Ali
  • 3,462
  • 4
  • 27
  • 55