Skip to content

Instantly share code, notes, and snippets.

@mluton
Created October 11, 2020 21:39
Show Gist options
  • Save mluton/2aef334885f203af40a2196b0485b0f3 to your computer and use it in GitHub Desktop.
Save mluton/2aef334885f203af40a2196b0485b0f3 to your computer and use it in GitHub Desktop.
Zoom and pan an image in a scroll view with Auto Layout
import UIKit
class ViewController: UIViewController {
let scrollView = UIScrollView()
let containerView = UIView()
let imageView = UIImageView(image: UIImage(named: "quita"))
override func viewDidLoad() {
super.viewDidLoad()
scrollView.translatesAutoresizingMaskIntoConstraints = false
containerView.translatesAutoresizingMaskIntoConstraints = false
scrollView.layer.borderWidth = 2.0
scrollView.layer.borderColor = UIColor.blue.cgColor
scrollView.delegate = self
view.addSubview(scrollView)
scrollView.addSubview(containerView)
containerView.addSubview(imageView)
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20.0),
containerView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
containerView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
containerView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
containerView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
containerView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor),
containerView.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor),
imageView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
imageView.topAnchor.constraint(equalTo: containerView.topAnchor)
])
}
override func viewDidLayoutSubviews() {
updateMinZoomScaleForSize(scrollView.frame.size)
}
func updateMinZoomScaleForSize(_ size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
}
extension ViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment