Digvijay Gida
Digvijay Gida

Reputation: 89

How to do zoom in, out in UIScrollView using UISlider?

Mainscroll is scrollview which was added into another internal UIView and i have UISlider to change internal view scale.

But, MainScroll.setZoomScale(CGFloat(sender.value), animated: true) this line is not work.

==> Here is my code.

override func viewDidLoad() {
    super.viewDidLoad()



    MainScroll.maximumZoomScale = 1
    MainScroll.minimumZoomScale = 10

    MainScroll.delegate = self

    MainScroll.zoomScale = 5
}

@IBAction func Scrolling(_ sender: UISlider) {

    MainScroll.setZoomScale(CGFloat(sender.value), animated: true)
}

Upvotes: 0

Views: 1003

Answers (1)

Alladinian
Alladinian

Reputation: 35636

Here is a minimal example for getting a UIScrollView to zoom.

The key is that you have to implement func viewForZooming(in scrollView: UIScrollView) -> UIView? and return a view (that is inside your scrollView) that is to be scaled (think of it like your 'document' or 'canvas' view).

Also, notice that zoom is working for the default pinch gestures on the scrollView as well.

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    // Assume that outlets exist on a storyboard
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var canvas: UIView! // A view that is added in the scrollView
    @IBOutlet var slider: UISlider!

    let minScale: CGFloat     = 1
    let maxScale: CGFloat     = 10
    let initialScale: CGFloat = 1

    override func viewDidLoad() {
        super.viewDidLoad()

        scrollView.delegate         = self

        scrollView.minimumZoomScale = minScale
        scrollView.maximumZoomScale = maxScale
        scrollView.zoomScale        = initialScale

        slider.minimumValue         = Float(minScale)
        slider.maximumValue         = Float(maxScale)
        slider.value                = Float(initialScale)
    }

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

    @IBAction func sliderValueChanged(_ sender: UISlider) {
        scrollView.zoomScale = CGFloat(sender.value)
    }

}

Upvotes: 2

Related Questions