效果如下:
ViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController<UIScrollViewDelegate> 4 @property (strong, nonatomic) UIScrollView *scrVCustom; 5 6 @end
ViewController.m
1 #import "ViewController.h" 2 3 @interface ViewController () 4 - (void)layoutUI; 5 - (void)scaleToBigDidPush:(UIButton *)sender; 6 - (void)scaleToSmallDidPush:(UIButton *)sender; 7 @end 8 9 @implementation ViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 14 [self layoutUI]; 15 } 16 17 - (void)didReceiveMemoryWarning { 18 [super didReceiveMemoryWarning]; 19 // Dispose of any resources that can be recreated. 20 } 21 22 - (void)layoutUI { 23 _scrVCustom = [[UIScrollView alloc] initWithFrame:CGRectInset(self.view.bounds, 0, 0)]; 24 //设置滚动视图_scrVCustom中的图片 25 UIImageView *imgVCustom = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CoolMan.jpg"]]; 26 [_scrVCustom addSubview:imgVCustom]; 27 28 _scrVCustom.contentSize = imgVCustom.bounds.size; 29 [self.view addSubview:_scrVCustom]; 30 31 //设置滚动视图_scrVCustom放大和缩小初始值 32 _scrVCustom.delegate = self; 33 _scrVCustom.minimumZoomScale = 0.2; 34 _scrVCustom.maximumZoomScale = 2.0; 35 _scrVCustom.zoomScale = 1.0; 36 37 CGFloat y = self.view.frame.size.height - 50; 38 UIButton *btnScaleToBig = [UIButton buttonWithType:UIButtonTypeCustom]; 39 btnScaleToBig.frame = CGRectMake(20, y, 80, 40); 40 [btnScaleToBig setTitle:@"放大" forState:UIControlStateNormal]; 41 [btnScaleToBig setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 42 [btnScaleToBig setBackgroundColor:[UIColor greenColor]]; 43 [btnScaleToBig addTarget:self 44 action:@selector(scaleToBigDidPush:) 45 forControlEvents:UIControlEventTouchUpInside]; 46 [self.view addSubview:btnScaleToBig]; 47 48 UIButton *btnScaleToSmall = [UIButton buttonWithType:UIButtonTypeCustom]; 49 btnScaleToSmall.frame = CGRectMake(120, y, 80, 40); 50 [btnScaleToSmall setTitle:@"缩小" forState:UIControlStateNormal]; 51 [btnScaleToSmall setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 52 [btnScaleToSmall setBackgroundColor:[UIColor greenColor]]; 53 [btnScaleToSmall addTarget:self 54 action:@selector(scaleToSmallDidPush:) 55 forControlEvents:UIControlEventTouchUpInside]; 56 [self.view addSubview:btnScaleToSmall]; 57 58 } 59 60 - (void)scaleToBigDidPush:(UIButton *)sender { 61 _scrVCustom.zoomScale += 0.2; //调整缩放值触发委托事件viewForZoomingInScrollView 62 } 63 64 - (void)scaleToSmallDidPush:(UIButton *)sender { 65 _scrVCustom.zoomScale -= 0.2; //调整缩放值触发委托事件viewForZoomingInScrollView 66 } 67 68 #pragma mark - ScrollView 69 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { 70 UIView *imgVCustom = nil; 71 for (id subview in scrollView.subviews) { 72 if ([subview isKindOfClass:[UIImageView class]]) { 73 imgVCustom = subview; 74 break; 75 } 76 } 77 return imgVCustom; 78 } 79 80 @end
时间: 2024-10-07 10:43:42