UIScrollView 缩放至某一区域
2023-06-06 本文已影响0人
大成小栈
UIScrollView 缩放很简单,设置以下必要代理、参数即可:
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
self.scrollView.maximumZoomScale = 15.0;
self.scrollView.minimumZoomScale = 0.2;
注:每次缩放只能操作一个View,同一层级的其他View呆在原地frame不变(scrollView承载的内容缩放,会使View移动,但其尺寸不变); demo中只缩放了imgTest并定位到其中的蓝色方框。
#import "ViewController2.h"
@interface ViewController2 ()<UIScrollViewDelegate>
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UIImageView *imgTest;
@property (strong, nonatomic) UIView *viewA;
@end
@implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_scrollView];
//设置代理对象
self.scrollView.delegate = self;
//设置缩放比例
self.scrollView.maximumZoomScale = 15.0;
self.scrollView.minimumZoomScale = 0.2;
self.scrollView.alwaysBounceVertical = YES;
self.scrollView.alwaysBounceHorizontal = YES;
self.scrollView.layer.borderColor = UIColor.redColor.CGColor;
self.scrollView.layer.borderWidth = 2.0;
//self.scrollView.bounces// 默认为yes
self.imgTest = [[UIImageView alloc] initWithFrame:_scrollView.bounds];
self.imgTest.image = [UIImage imageNamed:@"ScreenShot"];
[self.scrollView addSubview:_imgTest];
CGFloat blueViewHeight = 100;
CGSize size = self.imgTest.frame.size;
self.viewA = [[UIView alloc] initWithFrame:CGRectMake((size.width - blueViewHeight)/2, (size.height - blueViewHeight)/2, blueViewHeight, blueViewHeight)];
self.viewA.backgroundColor = UIColor.blueColor;
[self.imgTest addSubview:self.viewA];
}
//告诉UIScrollView 是哪个控件需要缩放
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return self.imgTest;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// // 移动至中心并放大
// CGRect scaleRect = [self.imgTest convertRect:_viewA.frame toView:self.scrollView];
// [self.scrollView zoomToRect:scaleRect animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// 移动至中心并放大
CGRect scaleRect = [self.imgTest convertRect:_viewA.frame toView:self.scrollView];
[self.scrollView zoomToRect:scaleRect animated:YES];
}
@end