从 UIScrollView 转发触摸 - UIButton 问题

Posted

技术标签:

【中文标题】从 UIScrollView 转发触摸 - UIButton 问题【英文标题】:Forwarding Touches From UIScrollView - UIButton Issues 【发布时间】:2012-09-11 17:18:27 【问题描述】:

我一直在试图弄清楚如何将触摸从 UIScrollView 转发到它的超级视图。原因是某种光标跟随触摸。无论如何,滚动视图都填充了 UIButtons。我转发触摸的代码是在滚动视图子类中使用委托:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    [super touchesBegan:touches withEvent:event];
    if ([[self tfDelegate]respondsToSelector:@selector(tfDelegateBegan:)]) 
        [[self tfDelegate]tfDelegateBegan:[touches anyObject]];
    
        NSLog(@"touches began");


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    [super touchesMoved:touches withEvent:event];
    if ([[self tfDelegate]respondsToSelector:@selector(tfDelegateMoved:)]) 
        [[self tfDelegate]tfDelegateMoved:[touches anyObject]];
    
        NSLog(@"touches moved");


-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    [super touchesEnded:touches withEvent:event];
    if ([[self tfDelegate]respondsToSelector:@selector(tfDelegateEnded:)]) 
        [[self tfDelegate]tfDelegateEnded:[touches anyObject]];
    
        NSLog(@"touches ended");


-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
    [super touchesCancelled:touches withEvent:event];
    if ([[self tfDelegate]respondsToSelector:@selector(tfDelegateCancelled:)]) 
        [[self tfDelegate]tfDelegateCancelled:[touches anyObject]];
    
        NSLog(@"touches cancelled");

但是,我了解到 UIScrollviews 通过 UIGestureRecognizers 操作,因此默认情况下甚至不会调用这些方法。我意识到手势识别器在 ios 5 中公开,但我也需要支持 4.0。我这样做了:

       NSArray *a = [[theScrollview gestureRecognizers]retain];
        for (UIGestureRecognizer *rec in a) 
            if ([rec isKindOfClass:[UIPanGestureRecognizer class]]) 
                NSLog(@"this is the pan gesture");
                rec.cancelsTouchesInView = NO;
            
        

这允许手势工作和触摸方法同时被调用。问题是,现在如果您在触摸按钮时尝试滚动,则可以在滚动时按下按钮。通常,滚动取消按钮,并且唯一可以按下按钮的时间是滚动视图没有滚动。 这是所需的功能。关于如何实现这一目标的任何建议?

【问题讨论】:

【参考方案1】:

也许可以尝试使用一个标志来控制按钮操作,如果滚动视图正在滚动,该标志会阻止事件触发。

BOOL isScrolling = NO;

- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView 
    isScrolling = YES;


- (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate 
    isScrolling = NO;


- (void) didTapButton 

    if(isScrolling)
        return;

    //Do Button Stuff

【讨论】:

以上是关于从 UIScrollView 转发触摸 - UIButton 问题的主要内容,如果未能解决你的问题,请参考以下文章

将事件从 UIScrollView 转发到 UIButton

使用后将覆盖 UIView 的触摸事件转发到下面的 UIScrollView

iOS 不会将触摸转发到以下视图

将触摸事件从 UIVew 传输到 UIScrollView

UIScrollView 触摸处理

UIScrollView 子视图上的触摸事件