Read this Ray Wenderlich tutorial:
http://www.raywenderlich.com/76436/use-uiscrollview-scroll-zoom-content-swift
If you go to the “Scrolling and zooming in a larger image” section, it will get the image up and allow you to pinch and zoom.
In case of changing the link, here is the basic information: Put this code in your view controller (this sets the basic functionality):
override func viewDidLoad() { super.viewDidLoad() // 1 let image = UIImage(named: "photo1.png")! imageView = UIImageView(image: image) imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:image.size) scrollView.addSubview(imageView) // 2 scrollView.contentSize = image.size // 3 var doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewDoubleTapped:") doubleTapRecognizer.numberOfTapsRequired = 2 doubleTapRecognizer.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(doubleTapRecognizer) // 4 let scrollViewFrame = scrollView.frame let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height let minScale = min(scaleWidth, scaleHeight); scrollView.minimumZoomScale = minScale; // 5 scrollView.maximumZoomScale = 1.0 scrollView.zoomScale = minScale; // 6 centerScrollViewContents() }
Add this to the class:
func centerScrollViewContents() { let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame }
And then this is if you want the double-tap sign to be recognized:
func scrollViewDoubleTapped(recognizer: UITapGestureRecognizer) { // 1 let pointInView = recognizer.locationInView(imageView) // 2 var newZoomScale = scrollView.zoomScale * 1.5 newZoomScale = min(newZoomScale, scrollView.maximumZoomScale) // 3 let scrollViewSize = scrollView.bounds.size let w = scrollViewSize.width / newZoomScale let h = scrollViewSize.height / newZoomScale let x = pointInView.x - (w / 2.0) let y = pointInView.y - (h / 2.0) let rectToZoomTo = CGRectMake(x, y, w, h); // 4 scrollView.zoomToRect(rectToZoomTo, animated: true) }
If you want to read the tutorial in more detail, but that pretty much covers it.
lg365 Nov 02 '15 at 14:20 2015-11-02 14:20
source share