- Platform: iOS8.0+
- Language: Swift3.0
- Editor: Xcode8
1.在storyboard上拖一个UIScrollView
2.再在UIScrollView中拖一个UIImageView
3.绑定@IBOutlet
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
// 约束 - 居中显示用
@IBOutlet weak var ivLeadingCons: NSLayoutConstraint!
@IBOutlet weak var ivTrailingCons: NSLayoutConstraint!
@IBOutlet weak var ivTopCons: NSLayoutConstraint!
@IBOutlet weak var ivBottomCons: NSLayoutConstraint!
4.添加方法
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scaleImageViewForAdjustingViewSize()
}
// 缩放到屏幕合适
fileprivate func scaleImageViewForAdjustingViewSize()
{
let minScale = min(view.bounds.size.width / imageView.bounds.size.width, view.bounds.size.height / imageView.bounds.size.height)
scrollView.minimumZoomScale = minScale //最小缩放值
scrollView.zoomScale = minScale //当前缩放值
}
// 居中显示
fileprivate func updateConstraintsForPositioningImageViewCenterly()
{
let yOffset = max(0, (view.bounds.size.height - imageView.frame.size.height)/2)
let xOffset = max(0, (view.bounds.size.width - imageView.frame.size.width)/2)
// 设置约束 - 相当于设置scrollview的contentsize,这样它才能滚动内容
ivTopCons.constant = yOffset
ivBottomCons.constant = yOffset
ivLeadingCons.constant = xOffset
ivTrailingCons.constant = xOffset
view.layoutIfNeeded()
}
extension ViewController: UIScrollViewDelegate{
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
updateConstraintsForPositioningImageViewCenterly()
}
}
5.Build and run to see what does it looks like.
如果对你有帮助,别忘了点个❤️哦。