Friday, July 6, 2012

Restricting diagonal scrolling in UIScrollview


#Restricting diagonal scrolling

enum EGRIDVIEW_SCROLLDIRECTION {
    eScrollLeft = 0,
    eScrollRight = 1,
    eScrollTop = 2,
    eScrollBottom = 3,
    eScrollNone = 4
    };

-(EGRIDVIEW_SCROLLDIRECTION) getScrollDirection : (CGPoint) startPoint endPoint:(CGPoint) endPoint
{
    EGRIDVIEW_SCROLLDIRECTION direction = eScrollNone;
   
    EGRIDVIEW_SCROLLDIRECTION xDirection;
    EGRIDVIEW_SCROLLDIRECTION yDirection;
   
    int xDirectionOffset = startPoint.x - endPoint.x;
    if(xDirectionOffset > 0)
        xDirection = eScrollLeft;
    else
        xDirection = eScrollRight;
   
    int yDirectionOffset = startPoint.y - endPoint.y;
    if(yDirectionOffset > 0)
        yDirection = eScrollTop;
    else
        yDirection = eScrollBottom;
   
    if(abs(xDirectionOffset) > abs(yDirectionOffset))
        direction = xDirection;
    else
        direction = yDirection;

    return direction;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    mPreviousTouchPoint = scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    CGPoint offset = self.scrollView.contentOffset;
   
    //Cool... Restricting diagonal scrolling
    mSwipeDirection = [self getScrollDirection:mPreviousTouchPoint endPoint:self.scrollView.contentOffset];
    switch (mSwipeDirection) {
        case eScrollLeft:
            self.scrollView.contentOffset = CGPointMake(offset.x, mPreviousTouchPoint.y);
            break;
           
        case eScrollRight:
            self.scrollView.contentOffset = CGPointMake(offset.x, mPreviousTouchPoint.y);
            break;
           
        case eScrollTop:
            self.scrollView.contentOffset = CGPointMake(mPreviousTouchPoint.x, offset.y);
            break;
           
        case eScrollBottom:
            self.scrollView.contentOffset = CGPointMake(mPreviousTouchPoint.x, offset.y);
            break;
           
        default:
            break;
    }
}

No comments:

Post a Comment