I am trying to implement the method scrollViewWillBeginDragging. When this method is called I check that the user has selected one of the buttons that are within the scrollview is in state:selected. If not then I display a UIAlert to inform the user.
My problem here is I only want to call the button selected (NextQuestion) method if the user scrolls from right to left (pulling the next view from the right). But if they are scrolling from Left to Right then I want it to scroll as normal.
At present the checker method is called no matter what direction the user scrolls in. How can I only call a method when they scroll from Right To Left?
Here is how i've currently implemented it:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self NextQuestion:scrollView];
}
-(IBAction)NextQuestion:(id)sender
{
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth) / pageWidth) + 1;
NSInteger npage = 0;
CGRect frame = scrollView.frame;
// Check to see if the question has been answered. Call method from another class.
if([QuestionControl CheckQuestionWasAnswered:page])
{
pageNumber++;
NSLog(@"Proceed");
if(([loadedQuestionnaire count] - 1) != page)
{
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}
// update the scroll view to the appropriate page
frame = scrollView.frame;
frame.origin.x = (frame.size.width * page) + frame.size.width;
frame.origin.y = 0;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
// If question has not been answered show a UIAlert with instructions.
else
{
UIAlertView *alertNotAnswered = [[UIAlertView alloc] initWithTitle:@"Question Not Answered"
message:@"You must answer this question to continue the questionnaire."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alertNotAnswered show];
}
}
Code for Solution 1:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
NSLog(@"%f",scrollView.contentOffset.x);
if (scrollView.contentOffset.x < lastOffset) // has scrolled left..
{
lastOffset = scrollView.contentOffset.x;
[self NextQuestion:scrollView];
}
}
In scrollViewWillBeginDragging
the scroll view has not yet moved (or registered the move) and so contentOffset
will by 0. As of IOS 5 you can instead look in the scrollview's panGestureRecognizer
to determine the direction and magnitude of the user's scrolling gesture.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];
if(translation.x > 0)
{
// react to dragging right
} else
{
// react to dragging left
}
}