在UIScrollView中劫持“滑动到下一页”

时间:2012-06-14 15:16:07

标签: objective-c ios uiscrollview


我想阻止在我的UIScrollview的第3页上滚动并“劫持滑动”手势触发某事。其他。在这个动作之后我想反应滚动。

这不起作用。

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    if(scrollView.contentOffset.x == self.view.frame.size.width * 2  ) {
        // disable scrolling
        scrollView.scrollEnabled = NO;
    }
}


// hijack the next scrolling event
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

当scrollEnabled = NO

时,不会调用此委托

感谢您的帮助


编辑不会调用EventHandler; - (

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Default background color
    self.view.backgroundColor = [UIColor redColor];

    // Create scroll view
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;


    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    recognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [scrollView addGestureRecognizer:recognizer];
    [recognizer release];
    [scrollView delaysContentTouches];

    // Create subviews (pages)
    NSInteger numberOfViews = 4;
    for (int i = 0; i < numberOfViews; i++) {
        // x pos
        CGFloat yOrigin = i * self.view.frame.size.width;

        // Create subview and add to scrollView
        UIView *pageView = [[UIView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
        pageView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];

        [scrollView addSubview:pageView];
        [pageView release];
    }

    // Set contentsize
    scrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);


    // Add scrollView to view and release
    [self.view addSubview:scrollView];
    [scrollView release];

}


-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    NSLog(@"swipe!!!!");
    scrollView.scrollEnabled = YES;
}

1 个答案:

答案 0 :(得分:2)

如果禁用滚动视图:

    scrollView.scrollEnabled = NO;

不可避免地调用委托方法,因此在处于劫持模式时需要另一种方法来处理滑动。您可以尝试使用UISwipeGestureRecognizer:而不是简单地禁用滚动,您可以将UISwipeGestureRecognizer关联到您的视图并处理来自处理程序方法的滑动:

UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
recognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:recognizer];

并在handleSwipeFrom中重新启用滚动:

-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    // do your hijack here
    scrollView.scrollEnabled = YES;
}