PmAbi1993
12/19/2017 - 6:21 AM

Image Inside ScrollView

A view or image inside scrolliew with a double tap configuration. Drop in replace mode..

         var scrollView : UIScrollView!
         var imageView : UIImageView!
        
        // inside viewDidload initialise the components
        scrollView = UIScrollView(frame: view.frame)
        scrollView.delegate = self
        imageView = UIImageView(frame: view.frame)
        imageView.contentMode = .scaleAspectFit
        scrollView.backgroundColor = UIColor.red
        view.addSubview(scrollView)
        scrollView.addSubview(imageView)
        imageView.image = UIImage(named: "jonSnow")
    
        scrollView.alwaysBounceVertical = false
        scrollView.alwaysBounceHorizontal = false
        scrollView.showsVerticalScrollIndicator = true
        scrollView.flashScrollIndicators()
        
        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 4.0

        let doubleTapGest = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapScrollView(recognizer:)))
        doubleTapGest.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer
        
        
        /* this function helps the double tap /*
        
         @objc func handleDoubleTapScrollView(recognizer: UITapGestureRecognizer) {
        if scrollView.zoomScale == 1 {
            scrollView.zoom(to: zoomRectForScale(scale: scrollView.maximumZoomScale, center: recognizer.location(in: recognizer.view)), animated: true)
        } else {
            scrollView.setZoomScale(1, animated: true)
        }
    }
     

    func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect {
        var zoomRect = CGRect.zero
        zoomRect.size.height = imageView.frame.size.height / scale
        zoomRect.size.width  = imageView.frame.size.width  / scale
        let newCenter = imageView.convert(center, from: scrollView)
        zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
        zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
        return zoomRect
    }
 /* this function helps the zooming of the image /*
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imageView
    }