I have searched many articles about UIScrollView
with an UIImageView
in, but all without AutoLayout
info. What I have done is: place a UIScrollView
in UIViewController
with constraints top 10, leading 10, bottom 50, trailing 10; place a UIImageView
inside of the UIScrollView
with constraints top 0, leading 0, bottom 0, trailing 0. What I want is simple: let my UIImageView
fit my UIScrollView
when app first loaded, and let my UIImageView
centered horizontally and vertically. Now I can see the image and just fit the screen nicely but the image is just at the top of UIScrollView
.(notes: in this circumstance, the width of my image after being zoomed to minimum zoomScale
equals to the width of UIScrollView
, the height of my image after being zoom to minimum zoomScale
less than the width of UIScrollView
. )
I really can't move my UIImageView
to center of UIScrollView
vertically and can not find where I made an error. Thanks a lot.
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
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
}
}
override func viewDidLayoutSubviews() {
let myImage = UIImage(named: "7.jpg")
imageView.image = myImage
let weightScale = scrollView.bounds.size.width / myImage!.size.width
let heightScale = scrollView.bounds.size.height / myImage!.size.height
let minScale = min(weightScale, heightScale)
let imagew = myImage!.size.width * minScale
let imageH = myImage!.size.height * minScale
let imageRect = CGRectMake(0, 0, imagew, imageH)
imageView.frame = imageRect
scrollView.contentSize = myImage!.size
scrollView.maximumZoomScale = 1.0
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
imageView.frame = imageRect
centerScrollViewContents()
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}