首页 > 代码库 > UIScrollView zoom in/out center

UIScrollView zoom in/out center

UIScrollView在放大的时候可以居中,但是缩小的时候总是跑到左上角,在网上找了好久,经过验证,以下是最完美的解决方案:

#pragma mark - UIScrollViewDelegate-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView{    for(UIView *view in scrollView.subviews)    {        if([view isMemberOfClass:[UIImageView class]])        {            return view;        }    }    return nil;}
// 使居中
-(void)scrollViewDidZoom:(UIScrollView *)scrollView{ CGFloat top = 0, left = 0; if (self.scrollView.contentSize.width < self.scrollView.bounds.size.width) { left = (self.scrollView.bounds.size.width-self.scrollView.contentSize.width) * 0.5f; } if (self.scrollView.contentSize.height < self.scrollView.bounds.size.height) { top = (self.scrollView.bounds.size.height-self.scrollView.contentSize.height) * 0.5f; } self.scrollView.contentInset = UIEdgeInsetsMake(top, left, top, left);}

 

UIScrollView zoom in/out center