向右和向左滚动子视图但不向上或向下滚动

时间:2016-04-21 00:02:18

标签: ios objective-c uiscrollview subview

我有一个视图的子视图 我希望用户能够将此视图仅向右和向左滚动。 但是当向上或向下滚动时,我希望这个视图留在它的位置,我不希望它移动。 我怎么能这样做?

我使用iOS iphone应用程序的目标c进行编码。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用UIScrollView并设置contentSize属性,使其height与您的观看次数height相同。

答案 1 :(得分:1)

  1. 创建panRecognizer

    UIPanGestureRecognizer *panRecognizer;
    panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                        action:@selector(wasDragged:)];
    [[self subview] addGestureRecognizer:panRecognizer];
    
  2. 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];
    }