I am building an application where I want to display a floor plan where the image is 1260x1000, larger than the size of my view controller. I want the user to be able to pan the image and zoom in and out, similar to how a map behaves in Mapview.
Below is the code in my view controller. When I run the simulator, the image is panning but the zooming in and out isn't working. Any suggestions on how to fix my code would be helpful.
class ViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(image: UIImage(named: "myMap.pdf"))
scrollView = UIScrollView(frame: view.bounds)
scrollView.contentSize = imageView.bounds.size
scrollView.addSubview(imageView)
scrollView.delegate = self
scrollView.minimumZoomScale = 0.3
scrollView.maximumZoomScale = 5
view.addSubview(scrollView)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
Your function signature is wrong:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
Note: If you want to be able to scale your pdf image while keeping the vector-based rendering (so it doesn't get blurry when zoomed), you should probably use PDFKit
and a PDFView
.
Add your myMap.pdf
file to your bundle... not to your Asset Catalog.
import UIKit
import PDFKit
class ZoomingPDFViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let fileURL = Bundle.main.url(forResource: "myMap", withExtension: "pdf") else {
fatalError("Could not load myMap.pdf!")
}
// Add PDFView to view controller.
let pdfView = PDFView(frame: self.view.bounds)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(pdfView)
// Load myMap.pdf file from app bundle.
pdfView.document = PDFDocument(url: fileURL)
pdfView.autoScales = true
pdfView.maxScaleFactor = 5.0
pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
}
}