【问题标题】:How to disable scroll in a specific subview of a UIScrollView如何在 UIScrollView 的特定子视图中禁用滚动
【发布时间】:2014-11-24 08:37:29
【问题描述】:

我有一个UIScrollView,其中包含许多子视图。其中一个子视图旨在显示折线图,因此用户可能需要水平拖动。事实上,当我的意思是水平拖动手指时,UIScrollView 的垂直滚动很容易激活。现在我想禁用图表子视图中的垂直滚动,并在其余部分保持活动状态。

我尝试将UIPanGestureRecognizer 添加到我的图表子视图中。它确实禁用了垂直滚动,但也禁用了水平滚动。我知道我可以在手势识别器的处理程序中编写代码来告诉我需要垂直或水平滚动。但是水平滚动实际上是由子视图的控制器管理的,它是一个第三方库(具体是JBChartView)。我想知道有没有简单的方法可以解决这个问题。

非常感谢。

【问题讨论】:

  • 如果您是两个可通过代码访问的滚动视图。您可以为您的内部 scrollView 实现一个委托方法,并使 y 位置不会改变。 (如果您编写代码),我可以为您提供更多帮助。
  • 您的滚动视图是否包含另一个带有折线图的滚动视图?

标签: ios objective-c uiscrollview uipangesturerecognizer


【解决方案1】:

感谢 Dev 和 Astoria,我已经解决了这个问题。现在我想在这里发布我的解决方案,以防有人遇到和我一样的问题。

结果如下:

因为Horizo​​ntal Only View 不是scrollView(实际上是JBLineChartView),所以最简单的scrollViewDidScroll 方式没有帮助。

我们仍然需要 GestureRecognizer 来实现这个目标,但是以更基本的方式,正如 Dev 所说,-touchesBegan 方法。遗憾的是 UIScrollView 不会响应这种触摸,我们需要为它写一个类别,如下代码:

@implementation UIScrollView (UITouchEvent)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
    self.scrollEnabled = YES;//This is the only line that you need to customize
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}
@end

哈,那就行了!

顺便说一句....这是我在 StackOverflow 上的第一个问题,这是一次非常愉快的旅程。

【讨论】:

  • 你怎么称呼 [[self nextResponder] touchesMoved:touches withEvent:event];来自 uiviewcontroller?
【解决方案2】:

使用 UIResponder 类的 -touchesBegan。如果触摸来自您的子视图(您不想滚动)。禁用滚动视图的滚动。 如果为该视图调用 -touchesEnded 或 -touchesCancelled。启用滚动视图的滚动。

【讨论】:

  • 这确实有效。但是 UIScrollView 不响应touchBegan。我必须写一个类别来扩展它。是否遗漏了什么,所以看起来有点不方便?
  • UIScrollView 不响应 -touchesBegan,但是对于子视图(UIView s),这将被触发。可以禁用 UIScrollView 的滚动,可以在 -touchesEnded 后启用。
【解决方案3】:

如果我没记错的话,您的主滚动视图包含另一个滚动视图,它是折线图的父级。在这种情况下,您可以使用 UIScrollViewDelegate 协议方法。当您开始滚动子视图时,只需禁用主滚动视图。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
  if(scrollView==self.lineChartParent)
    self.mainScrollView.scrollingEnabled = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
  if(scrollView==self.lineChartParent)
    self.mainScrollView.scrollingEnabled = YES;
}

【讨论】:

  • 这应该可以工作..您还可以为两个滚动视图分配标签并通过检查标签来采取行动...就像这里所做的那样。
  • 这是一个不错的方法。但是,lineChartParent 不是 ScrollView,因此它不会对滚动操作做出反应。太遗憾了。但这也是一个不错的方法。下次我会尝试使用这种方法。非常感谢。
猜你喜欢
  • 2012-10-21
  • 2021-11-23
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
相关资源
最近更新 更多