iOS ScrollView 下拉放大

定义变量

{
    UIImageView *_zoomView;
    BOOL _zoomIn;
    CGSize _contentSize;
    CGFloat _zoomHeight;
    BOOL _decelerating;
}

初始化

    UIImage *img = [UIImage imageNamed:@"blackeye.jpg"];
    
    _contentSize = CGSizeMake(0, img.size.height);
    _zoomHeight = 200;
    
    self.scrollView.contentInset = UIEdgeInsetsMake(_zoomHeight, 0, 0, 0);
    _zoomView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -_zoomHeight, self.scrollView.bounds.size.width, 200)];
    _zoomView.backgroundColor = [UIColor purpleColor];
    [self.scrollView addSubview:_zoomView];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
    imageView.image = img;
    [self.scrollView addSubview:imageView];
    
    self.scrollView.contentSize = _contentSize;
    
    self.scrollView.delegate = self;

处理滚动

#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offsetY = scrollView.contentOffset.y;
    NSLog(@"offsetY: %f",offsetY);
    
    CGFloat top = scrollView.contentInset.top;
    
    
    if (!_zoomIn) {
        if (offsetY < -top) { // 下拉
            CGRect frame = _zoomView.frame;
            frame.origin.y = offsetY;
            frame.size.height = -offsetY;
            _zoomView.frame = frame;
            
            if (!_decelerating && -offsetY > 1.9 * _zoomHeight) {
                scrollView.contentInset = UIEdgeInsetsMake(scrollView.bounds.size.height, 0, 0, 0);
                frame.origin.y = -scrollView.bounds.size.height;
                frame.size.height = scrollView.bounds.size.height;
                _zoomView.frame = frame;
                
                _zoomIn = YES;
                scrollView.contentSize = CGSizeMake(0, 1); // 使上拉有弹簧效果
            }
        }
    } else { // 上拉
        if (!_decelerating && (offsetY + top) / top > 0.3) {
            
            scrollView.contentInset = UIEdgeInsetsMake(_zoomHeight, 0, 0, 0);
            CGRect frame = _zoomView.frame;
            frame.origin.y = -_zoomHeight;
            frame.size.height = _zoomHeight;
            _zoomView.frame = frame;
            
            _zoomIn = NO;
            scrollView.contentSize = CGSizeMake(0, _contentSize.height); // 恢复正常
        }
    }
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    _decelerating = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _decelerating = NO;
}

 

posted @ 2018-05-18 13:42  Emerys  阅读(256)  评论(0编辑  收藏  举报