Nor*_*Big 1 uiscrollview uiimageview ios autolayout swift
找遍了对多篇UIScrollView
与UIImageView
中,但都没有AutoLayout
信息.我所做的是:地方UIScrollView
在UIViewController
与约束前10名,领先的10,底部50,落后10; 放置UIImageView
在UIScrollView
约束前面0,前面0,下面0,尾随0.我想要的很简单:让我的UIImageView
适合我的UIScrollView
应用程序第一次加载时,让我的UIImageView
水平和垂直居中.现在我可以看到图像并恰好适合屏幕,但图像位于顶部UIScrollView
.(注意:在这种情况下,我的图像宽度在缩放到最小值后zoomScale
等于宽度UIScrollView
,我的图像高度在缩放到最小值zoomScale
小于宽度之后UIScrollView
.)我真的无法将我移动UIImageView
到UIScrollView
垂直中心,无法找到我发生错误的地方.非常感谢.
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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
小猪支持pic-o-matic的回答.我有一个案例,我需要将图像居中,只要它小于滚动视图框架.使用插图为简单的解决方案.
if imageView.frame.height <= scrollView.frame.height {
let shiftHeight = scrollView.frame.height/2.0 - scrollView.contentSize.height/2.0
scrollView.contentInset.top = shiftHeight
}
if imageView.frame.width <= scrollView.frame.width {
let shiftWidth = scrollView.frame.width/2.0 - scrollView.contentSize.width/2.0
scrollView.contentInset.left = shiftWidth
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6451 次 |
最近记录: |