Just trying to figure out a way to make a ordinary photo viewer for iPhone and I just couldn't make the zooming work.
myimageview = UIImageView()
myimageview.translatesAutoresizingMaskIntoConstraints = false
myimageview.image = UIImage(named: "1")
scrollview = UIScrollView()
scrollview.delegate = self
scrollview.backgroundColor = UIColor.brownColor()
scrollview.minimumZoomScale = self.view.frame.width/myimageview.image!.size.width
scrollview.maximumZoomScale = 1.0
scrollview.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(scrollview)
scrollview.addSubview(myimageview)
let views = ["scrollview":scrollview,"myimageview":myimageview]
//add scrollview constraints
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollview]|", options: [], metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollview]|", options: [], metrics: nil, views: views))
scrollview.contentSize = myimageview.image!.size
//add contentview:myimageview constraints
let imagesize = myimageview.image!.size
//let dd = (self.view.frame.height-imagesize.height*self.view.frame.width/imagesize.width)/2
scrollview.addConstraint(NSLayoutConstraint(item: myimageview, attribute: .CenterY, relatedBy: .Equal, toItem: scrollview, attribute: .CenterY, multiplier: 1.0, constant: 0))
scrollview.addConstraint(NSLayoutConstraint(item: myimageview, attribute: .Left, relatedBy: .Equal, toItem: scrollview, attribute: .Left, multiplier: 1.0, constant: 0))
scrollview.addConstraint(NSLayoutConstraint(item: myimageview, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: myimageview.image!.size.width))
scrollview.addConstraint(NSLayoutConstraint(item: myimageview, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: myimageview.image!.size.height))
So basically, I got a scrollview and I got an imageview and I added it to the subviews of uiscrollview. And I manually set the contentsize of the scrollview and I set the zooming. I also added the viewForZoomingInScrollView delegate function. Zooming works fine.
Problem: when zoom out, I want the image to show in the middle of the screen(uiscrollview) but now it's on the top. As you can see below, the picture is on the top, I want it to be in the middle of the screen. It seems the CenterY doesn't work. No error has been found. The code I pasted is in the ViewDidLoad function.
Ok, I found that still, after 2 yrs, autolayout can't solve this problem, you had to write it manually. Very sad.