ios – 启用了内容插入的UIScrollView分页工作很奇怪

前端之家收集整理的这篇文章主要介绍了ios – 启用了内容插入的UIScrollView分页工作很奇怪前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了具有内容插入的UIScrollView.
scrollView.frame = CGRectMake(-80,180,480,190)
self.scrollView.contentInset = UIEdgeInsetsMake(0,160,160);
self.scrollView.pagingEnabled = YES;
[self.scrollView setContentSize:CGSizeMake(480,190)];

// Add three Views
[self.scrollView addSubview:view1];
[self.scrollView addSubview:view2];
[self.scrollView addSubview:view3];

[view1 setFrame:CGRectMake(0,190)];
[view2 setFrame:CGRectMake(160,190)];
[view3 setFrame:CGRectMake(320,190)];

第一次,scrollView.contentOffset.x为-160.0

但是奇怪的问题是当我点击scrollView(黄色区域)时,内容偏移x值将重置为0并显示为这样.

我尝试过几次,但是点击滚动视图会将内容偏移量重置为0.

我该如何防止这种情况?

解决方法

UIScrollView分页通过滚动与scrollView宽度相同的页面(在您的情况下为480个宽度的页面).这意味着您有1个单页(由于160内容插入,您仍然可以左右滚动).

做这项工作的一个方法是:

self.scrollView.frame = CGRectMake(80,190);
self.scrollView.clipsToBounds = NO;
self.scrollView.contentInset = UIEdgeInsetsZero;
self.scrollView.pagingEnabled = YES;
[self.scrollView setContentSize:CGSizeMake(480,190)];

这将绘制和滚动正确,但是,屏幕的两侧将不会互动(每边80个像素,因为控件从frame.origin.x = 80开始,结束于80 160 = 240).

第二个选项是通过使用UIScrollViewDelegate提供的方法来处理分页.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // pageIndex must be declared as a class member - this is used to prevent skipping pages during scroll
    pageIndex = 0;
    self.scrollView.frame = CGRectMake(0,320,190);
    self.scrollView.contentInset = UIEdgeInsetsMake(0,80,80);
    self.scrollView.pagingEnabled = NO;
    self.scrollView.clipsToBounds = YES;
    [self.scrollView setContentSize:CGSizeMake(480,190)];
    self.scrollView.delegate = self;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    int pageWidth = 160;
    int pageX = pageIndex*pageWidth-scrollView.contentInset.left;
    if (targetContentOffset->x<pageX) {
        if (pageIndex>0) {
            pageIndex--;
        }
    }
    else if(targetContentOffset->x>pageX){
        if (pageIndex<3) {
            pageIndex++;
        }
    }
    targetContentOffset->x = pageIndex*pageWidth-scrollView.contentInset.left;
    NSLog(@"%d %d",pageIndex,(int)targetContentOffset->x);
}
原文链接:https://www.f2er.com/iOS/328789.html

猜你在找的iOS相关文章