miss h
miss h

Reputation: 131

scroll a subview right and left but not up or down

I have a subview of a view I want the user to be abel to scroll this view to the right and left only. But when scrolling up or down I want this view to stay on it's place I don't want it to move. How can I do that?

I am coding using objective c for iOS iphone app.

Thanks

Upvotes: 0

Views: 63

Answers (2)

Saraswati
Saraswati

Reputation: 1526

  1. Create panRecognizer

    UIPanGestureRecognizer *panRecognizer;
    panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                        action:@selector(wasDragged:)];
    [[self subview] addGestureRecognizer:panRecognizer];
    

2.Create wasDragged method

 - (void)wasDragged:(UIPanGestureRecognizer *)recognizer {

    CGPoint translation = [recognizer translationInView:self.view];
    CGRect recognizerFrame = recognizer.view.frame;
    recognizerFrame.origin.x += translation.x;


    // Check if UIImageView is completely inside its superView
    if (CGRectContainsRect(self.view.bounds, recognizerFrame)) {
        recognizer.view.frame = recognizerFrame;
    }
    // Else check if UIImageView is vertically and/or horizontally outside of its
    // superView. If yes, then set UImageView's frame accordingly.
    // This is required so that when user pans rapidly then it provides smooth translation.
    else {
        // Check vertically
        if (recognizerFrame.origin.y < self.view.bounds.origin.y) {
            recognizerFrame.origin.y = 0;
        }
        else if (recognizerFrame.origin.y + recognizerFrame.size.height > self.view.bounds.size.height) {
            recognizerFrame.origin.y = self.view.bounds.size.height - recognizerFrame.size.height;
        }

        // Check horizantally
        if (recognizerFrame.origin.x < self.view.bounds.origin.x) {
            recognizerFrame.origin.x = 0;
        }
        else if (recognizerFrame.origin.x + recognizerFrame.size.width > self.view.bounds.size.width) {
            recognizerFrame.origin.x = self.view.bounds.size.width - recognizerFrame.size.width;
        }
    }

    // Reset translation so that on next pan recognition
    // we get correct translation value
    [recognizer setTranslation:CGPointZero inView:self.view];
}

Upvotes: 1

Evan
Evan

Reputation: 202

You can use a UIScrollView and set the contentSize property so that its height is the same as your view's height.

Upvotes: 1

Related Questions