Subclassed UIScrollView检测按钮内的触摸,但对用户交互没有反应

时间:2016-03-25 17:05:26

标签: ios objective-c iphone uiscrollview

我有一个垂直的UIScrollView,它有几个大按钮占据了滚动视图中的大部分空间。出于这个原因,我必须在这篇文章ios 8 - buttons in horizontal scroll view intercepting pan event - scroll does not work之后继承滚动视图并覆盖以下类方法:

- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
    static int count = 0;
    count++;
    NSLog(@"calling this function 2");
    NSLog(@"count = %d", count);
    UITouch *touch = [touches anyObject];

    if(touch.phase == UITouchPhaseMoved)
    {
        NSLog(@"UITouchPhaseMoved so returning no");
        return NO;
    }


    else
    {
        NSLog(@"returning super");
        NSLog(@"returning whatever this value is %d 0/1", [super touchesShouldBegin:touches withEvent:event inContentView:view]);
        [super touchesShouldBegin:touches withEvent:event inContentView:view];
        return [super touchesShouldBegin:touches withEvent:event inContentView:view];
    }
}

当我运行我的应用程序时,在点击按钮时调用上面的函数,但是当我在滚动视图中的任何位置拖动按钮内部或外部时,不会调用该函数。无论我在哪里拖动,滚动视图都不会滚动。

这是我与滚动视图相关的所有代码(它是用IB设置的):

            smallView.scrollEnabled = YES;
            smallView.contentSize = CGSizeMake(smallView.frame.size.width, smallView.frame.size.height*1.4);
            smallView.delegate = self;

以下是与按钮相关的代码,以防万一:

NSArray *buttonsArray = @[button1, button2, button3, button4, button5];
for (int i = 0; i < [buttonsArray count]; i++) {
    UIButton *button = buttonsArray[i];
    button.tag = i+1;
    [button addTarget:self action:@selector(p_motivationButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
}

为什么我的滚动视图没有滚动,甚至没有调用touchesShouldBegin

1 个答案:

答案 0 :(得分:0)

子类UIScrollView并覆盖touchesShouldCancelInContentView(),如下所示:

override func touchesShouldCancelInContentView(view: UIView) -> Bool {
    if let _ = view as? UIControl {
        return true
    }
    else {
        return super.touchesShouldCancelInContentView(view)
    }
}