当scrollView设置为pagingEnabled为YES

时间:2016-11-21 07:40:29

标签: ios objective-c uiscrollview uiscrollviewdelegate

当我点击ScrollView时,即使scrollViewWillBeginDecelerating设置为scrollViewDidEndDeceleratingscrollView's

,也会调用方法pagingEnabledYES

scrollView subViews并尝试根据contentOffset设置subViews。但它不起作用。

这是我的代码:

self.myScrollView.frame = CGRectMake(0, 0, pageWidth, pageHeight);
self.myScrollView.contentSize = CGSizeMake(pageWidth * self.contentViewControllers.count, pageHeight);

for (NSInteger i = 0; i < self.contentViewControllers.count; i++) {
    UILabel *label = [UILabel new];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"Page %ld",i];
    label.backgroundColor = [UIColor randomColor];
    label.frame = CGRectMake(i * pageWidth, 0, pageWidth, pageHeight);
    [self.myScrollView addSubview:label];
}

self.myScrollView.contentInset = UIEdgeInsetsMake(120, 0, 0, 0);
self.myScrollView.contentOffset = CGPointMake(0, - 120);
self.myScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(120, 0, 0, 0);

- (UIScrollView *)myScrollView{
if (!_myScrollView) {
    _myScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    _myScrollView.backgroundColor = [UIColor blackColor];
    _myScrollView.pagingEnabled = YES;
    _myScrollView.directionalLockEnabled = YES;
    _myScrollView.delegate = self;
    //_myScrollView.delaysContentTouches = NO;
    //_myScrollView.scrollsToTop = NO;
}

return _myScrollView;
}

当我点击subView内的任何scrollView时,它会调用委托方法:

scrollViewWillBeginDecelerating&gt;&gt; scrollViewDidScroll&gt;&gt; scrollViewDidEndDecelerating

contentOffset更改为{0,0}

1 个答案:

答案 0 :(得分:0)

请更新您的代码:

请在for循环后设置contentSize。

self.myScrollView.frame = CGRectMake(0, 0, pageWidth, pageHeight);

for (NSInteger i = 0; i < self.contentViewControllers.count; i++) {
    UILabel *label = [UILabel new];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"Page %ld",i];
    label.backgroundColor = [UIColor randomColor];
    label.frame = CGRectMake(i * pageWidth, 0, pageWidth, pageHeight);
    [self.myScrollView addSubview:label];
}

self.myScrollView.contentInset = UIEdgeInsetsMake(120, 0, 0, 0);
self.myScrollView.contentOffset = CGPointMake(0, - 120);
self.myScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(120, 0, 0, 0);

self.myScrollView.contentSize = CGSizeMake(pageWidth * self.contentViewControllers.count, pageHeight);

- (UIScrollView *)myScrollView{
if (!_myScrollView) {
    _myScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    _myScrollView.backgroundColor = [UIColor blackColor];
    _myScrollView.pagingEnabled = YES;
    _myScrollView.directionalLockEnabled = YES;
    _myScrollView.delegate = self;
    //_myScrollView.delaysContentTouches = NO;
    //_myScrollView.scrollsToTop = NO;
}

return _myScrollView;
}