UIScrollView根据点击中心放大缩小视图

关键代码
继承UIScrollViewDelegate协议,重写viewForZooming,scrollViewDidZoom两个方法

extension ScrollView: UIScrollViewDelegate {
    
    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView //被放大缩小的视图
    }
    
    // 重置imageView的中心
    public func scrollViewDidZoom(_ scrollView: UIScrollView) {
        
        let offsetX = max((bounds.width - contentSize.width) * 0.5, 0)
        let offsetY = max((bounds.height - contentSize.height) * 0.5, 0)
        
        imageView.center = CGPoint(x: contentSize.width * 0.5 + offsetX, y: contentSize.height * 0.5 + offsetY)
    }
}

UIScrollView要放大缩小,必须设置maximumZoomScaleminimumZoomScale

UIScrollView添加双击手势

lazy var doubleTapGestureRecognizer: UITapGestureRecognizer = { [weak self] in      
      let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ZoomingImageView.doubleTapped(_:)))
      gestureRecognizer.numberOfTapsRequired = 2
      return gestureRecognizer
}()

双击之后触发的方法

@objc fileprivate func doubleTapped(_ gestureRecognizer: UITapGestureRecognizer) {
      let location = gestureRecognizer.location(in: imageView)
      if zoomScale > minimumZoomScale {
          setZoomScale(minimumZoomScale, animated: true)
      } else {
          zoom(to: CGRect(x: location.x, y: location.y, width: 1, height: 1), animated: true)
      }
}

你可能感兴趣的:(UIScrollView根据点击中心放大缩小视图)