我的应用程序调用scrollViewDidScroll 19次

joe*_*oec 9 exc-bad-access objective-c uiscrollview ios4

我有一个基于Apple的PageControl示例的应用程序.第一次加载视图时,滚动视图将加载第0页和第1页.每当启动滚动时,UIKit应该调用scrollViewDidScroll方法吗?

当启动从第0页到第1页的滚动时,应用程序应加载第1页,页面和页面+ 1,(以防止在滚动期间闪烁).

我的应用程序似乎调用了scrollViewDidScroll19次,我的loadScrollViewWithPage:方法每次调用19次,第0页和第1页,在它最终到达第1页和第2页之前,然后它崩溃了.

这些是方法:

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    NSLog(@"scrollviewdidscroll");
   // We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
   // which a scroll event generated from the user hitting the page control triggers updates from
   // the delegate method. We use a boolean to disable the delegate logic when the page control is used.
   if (pageControlUsed) {
        // do nothing - the scroll was initiated from the page control, not the user dragging
       return;
   }

   // Switch the indicator when more than 50% of the previous/next page is visible
   CGFloat pageWidth = scrollView.frame.size.width;
   int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
   pageControl.currentPage = page;

   // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
   [self loadScrollViewWithPage:page - 1];
   [self loadScrollViewWithPage:page];
   [self loadScrollViewWithPage:page + 1];

   // A possible optimization would be to unload the views+controllers which are no longer visible
}

- (void)loadScrollViewWithPage:(int)page {
    if (page < 0) return;
    if (page >= kNumberOfPages) return;

    NSLog(@"page: %i", page);

    // replace the placeholder if necessary
    KeyboardViewController *controller = [viewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null]) {
        controller = [[KeyboardViewController alloc] initWithPageNumber:page];
        [viewControllers replaceObjectAtIndex:page withObject:controller];
        [controller release];
    }

    // add the controller's view to the scroll view
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    frame.size.height = scrollView.frame.size.height;
    controller.view.frame = frame;
    [scrollView setAutoresizesSubviews:YES];
    [scrollView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
    [scrollView addSubview:controller.view];
}
Run Code Online (Sandbox Code Playgroud)

为什么scrollViewDidScroll被调用了这么多次?

谢谢

Jos*_*erg 28

scrollViewDidScroll:每次滚动边界改变时都会调用它.这意味着它在滚动期间以及启动时被调用.你可能想尝试一下scrollViewWillBeginDragging:.