iOS 用ScrollerView实现图片分页同时可缩放的功能

写了一个类似今日头条查看图片的Demo,功能实现:
1.分页
2.每个分页界面可以缩放及移动
效果: http://v.youku.com/v_show/id_XMzMyNjQ1MjY5Ng==.html?spm=a2h3j.8428770.3416059.1
实现过程:

  • 先创建一个容器ScrollerView(self.dataSource为数据源,存放图片名称);
//容器ScrollerView
@property (nonatomic,strong) UIScrollView * mainScroll;
//数据源
@property (nonatomic,strong) NSArray * dataSource;
//翻页后的页码
@property (nonatomic,assign) NSInteger num;
//翻页前的页码
@property (nonatomic,assign) NSInteger oldNum;

#pragma mark - get
-(UIScrollView *)mainScroll{
    if (!_mainScroll) {
        _mainScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, MAIN_W, MAIN_H)];
        _mainScroll.delegate = self;
        //打开分页
        _mainScroll.pagingEnabled = YES;
        _mainScroll.scrollEnabled = YES;
        _mainScroll.showsVerticalScrollIndicator = NO;
        _mainScroll.showsHorizontalScrollIndicator = NO;
        _mainScroll.contentSize = CGSizeMake(MAIN_W * self.dataSource.count, 0);
    }
    return _mainScroll;
}
  • 容器ScrollerView进行分页之后,每一个页面又是一个子ScrollerView,然后在子ScrollerView中添加ImageView;
for (int i = 0; i < self.dataSource.count; i ++) {
        UIScrollView * mScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(MAIN_W * i, 0, MAIN_W, MAIN_H)];
        mScroll.delegate=self;
        //最大缩放值
        mScroll.maximumZoomScale=2.0;
       //最小缩放值
        mScroll.minimumZoomScale=1.0;
        mScroll.showsVerticalScrollIndicator = NO;
        mScroll.showsHorizontalScrollIndicator = NO;
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, MAIN_W, MAIN_H)];
        imageView.tag = 1000+i;
        mScroll.tag = 2000+i;
        imageView.image = [UIImage imageNamed:self.dataSource[i]];
        [mScroll addSubview:imageView];
        [self.mainScroll addSubview:mScroll];
    }
    [self.view addSubview:self.mainScroll];
  • 多个ScrollerView继承代理,所以在代理方法中要分清;
#pragma mark - UIScrollerViewDelegate 
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.mainScroll) {
        self.num = scrollView.contentOffset.x/MAIN_W;
        NSLog(@"%ld",self.num);
        //如果页码切换了,前一张图片恢复1.0比例
        if (self.oldNum != self.num) {
            UIScrollView * sc = [self.view viewWithTag:2000+self.oldNum];
            sc.zoomScale = 1.0;
        }
        self.oldNum = self.num;
    }
}

//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    if (scrollView != self.mainScroll) {
       //  返回需要缩放的控件
        return [self.view viewWithTag:1000+self.num];
    }
    return nil;
}

你可能感兴趣的:(iOS 用ScrollerView实现图片分页同时可缩放的功能)