在 ScrollView 中缩放图像

Zoom images in ScrollView

我有一个滚动视图,里面有一些图像,我水平滚动。我想使用捏合手势进行缩放。这是我正在使用的代码,但它不起作用。我似乎无法弄清楚我做错了什么。有什么建议吗?

let scrollView = UIScrollView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.size.width , height: (UIScreen.main.bounds.size.height - 140))) var frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
var subView = UIImageView()
override func viewDidLoad() {
   super.viewDidLoad()
   getOfferImages()
   swipeGesture()
   setupView()
   scrollView.delegate = self
   scrollView.minimumZoomScale = 1.0
   scrollView.maximumZoomScale = 4.0
 }
 func configureScrollView(){

   scrollView.backgroundColor = UIColor.black
   scrollView.showsHorizontalScrollIndicator = false
   scrollView.isUserInteractionEnabled = true
   scrollView.clipsToBounds = true
   scrollView.bouncesZoom = true

   pageNumberlabel.text = "1 of \(offersImagesArray.count)"
   self.view.addSubview(scrollView)

   for index in 0..<images.count {

       frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
       frame.size = self.scrollView.frame.size
       subView = UIImageView(frame: frame)
       subView.tag = 1
       subView.contentMode = .scaleToFill
       subView.isUserInteractionEnabled = true
       subView.sd_setImage(with: images[index], placeholderImage: UIImage(named:""), options: [.continueInBackground])
       self.scrollView.addSubview(subView)
   }
   self.scrollView.isPagingEnabled = true
   self.scrollView.contentSize = CGSize(width: (self.scrollView.frame.size.width *  CGFloat(images.count)), height: self.scrollView.frame.size.height)

 }
 func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
  // let image = self.view.findSubview(withTag: 1)
   return self.subView
 }

您需要将 PinchGestureRecognizer 添加到故事板,然后 link 将其添加到如下函数中。

@IBAction func scaleImage(_ sender: UIPinchGestureRecognizer) {
    self.subView.transform = self.subView.transform.scaledBy(x: sender.scale, y: sender.scale)
    sender.scale = 1
}

注意:subView 应替换为您尝试缩放的视图。

1) 设置缩放比例

scrollView.maximumZoomScale = 10
scrollView.minimumZoomScale = 1

2) 设置滚动视图委托,return 你在 viewForZooming 中的图像

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return myImageView
}