【问题标题】:scroll a subview right and left but not up or down向右和向左滚动子视图,但不能向上或向下滚动
【发布时间】:2016-04-21 00:02:17
【问题描述】:

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

我正在使用 iOS iphone 应用程序的 Objective c 进行编码。

谢谢

【问题讨论】:

    标签: ios objective-c uiscrollview subview


    【解决方案1】:

    您可以使用UIScrollView 并设置contentSize 属性,使其height 与您视图的height 相同。

    【讨论】:

    • 你不明白我的意思,我想要一个可以滚动但只能左右滚动的小 ui 视图。如果用户向上向下滚动我想留在顶部栏下,我不希望它从它的位置移动
    【解决方案2】:
    1. 创建 panRecognizer

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

    2.创建wasDragged方法

     - (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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-05
      • 2015-09-09
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      相关资源
      最近更新 更多