iOS uses UIScorllView to realize two finger scaling function

  • 2021-12-13 09:51:40
  • OfStack

The two-finger zoom function can be realized not only by UIPinchGestureRecognizer gesture, but also by UIScorllView. UIScrollView can easily realize the maximum and minimum zoom values and scroll effect. The code is as follows:


#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  _scrollView.minimumZoomScale = 1.0;   //  Minimum scaling value 
  _scrollView.maximumZoomScale = 10.0;  //  Maximum scaling value 
  [_scrollView setZoomScale:_scrollView.minimumZoomScale];  //  Initial scaling value 
  _scrollView.delegate = self;
  _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
  _imageView.frame = self.view.frame;
  [_scrollView addSubview:_imageView];
}
#pragma mark -  Returns the control that needs to be scaled 
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
  return _imageView;
}
- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
}
@end

The key point is to call the viewForZoomingInScrollView: proxy method, which returns the control that needs to be scaled.

GitHub Address for Demo


Related articles: