contentInset
API里系统的注释翻译应该是,在content周围增加附加的可以滑动的区域。我的理解是,在原来contentSize的size外围再增加上contentInset的滑动区域。
UIScrollView *sc = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
sc.backgroundColor = [UIColor redColor];
sc.center = self.view.center;
[self.view addSubview:sc];
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
img.image = [UIImage imageNamed:@"小猪"];
[sc addSubview:img];
sc.contentSize = img.frame.size;
然后添加contentInset
sc.contentInset = UIEdgeInsetsMake(10, 20, 30, 40);
从效果可以看出,上左下右分别多出10,20,30,40的滚动区域。而这时候的contentSize和contentOffset还是(300,300)和(0,0)吗? 打断点看一下:
(lldb) po sc.contentSize
(width = 300, height = 300)
(lldb) po sc.contentOffset
(x = 0, y = 0)
可见contentSize并没有变大,而contentOffset是以contentSize的原点来计算的。
UIScrollView缩放
实现滚动视图的缩放,至少需要满足三个条件:
1. 设定最小缩放属性minimumZoomScale 默认为1
2. 设定最小缩放属性maximumZoomScale 默认为1
3. 实现UIScrollViewDelegate代理方法 viewForZoomingInScrollView
@interface ViewController ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIImageView *imageView;
``
self.imageView = img;
sc.delegate = self;
sc.minimumZoomScale = 1.0;
sc.maximumZoomScale = 10.0;
``
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return self.imageView;
}
然后,这时候我们来测试一个问题,将图片坐标改小,居中,然后放大:
sc.contentSize = img.frame.size;
sc.contentInset = UIEdgeInsetsZero;
img.frame = CGRectMake(0, 0, 200, 300);
sc.frame.size.height/2);
问题如图:放大的图片一直在往右边偏移,
在代理方法scrollViewDidEndZooming里打断点来看一下img的center
(lldb) po img.frame
(origin = (x = 50, y = 0), size = (width = 200, height = 300))
(lldb) po self.imageView.frame
(origin = (x = 50, y = 0), size = (width = 307.18706359518728, height = 460.78059539278087))
可以看到,img的原点坐标没有变化,所以导致了图片放大右移不居中。解决方法如下:
//让图片居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
(scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
(scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
self.imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
scrollView.contentSize.height * 0.5 + offsetY);
}
有时候需要实现,双击放大图片缩小图片等,可能需要用到这两个方法
- (void)setZoomScale:(CGFloat)scale animated:(BOOL)animated NS_AVAILABLE_IOS(3_0);
- (void)zoomToRect:(CGRect)rect animated:(BOOL)animated NS_AVAILABLE_IOS(3_0);
zoomToRect: animated:,把从scrollView里截取的矩形区域缩放到整个scrollView当前可视的frame里面。如果截取的区域大于scrollView的frame时,图片缩小。
sc.minimumZoomScale = 0.1;
[sc zoomToRect:CGRectMake(0, 0, 500, 500) animated:YES];