我在 Storyboard中定义了一个带有 socket 的 UIScrollView。这个 ScrollView 通过代码(不在 Storyboard上)添加了一个 UIImageView 。当我运行该应用程序时,图像会超出纵横比。一旦我触摸缩放图像,它就会捕捉到正确的宽高比。
这是怎么回事?!
@IBOutlet var scrollView: UIScrollView!
var imageView = UIImageView()
var selectedImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
imageView.image = selectedImage
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
scrollView.contentMode = .ScaleAspectFit
scrollView.addSubview(imageView)
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleHeight, scaleWidth)
scrollView.minimumZoomScale = 0.3
scrollView.maximumZoomScale = 1
scrollView.zoomScale = minScale
centerScrollViewContents()
self.closeBtn.layer.cornerRadius = CGRectGetWidth(self.closeBtn.frame)/20.0
}
几乎固定: 我编辑了代码以在 viewWillLayoutSubviews 而不是 viewDidLoad 中定义 imageView.frame,如下面的答案中所建议的。我现在遇到了一个新问题 - 图像无法放大...它允许您缩放,直到松开手指,然后它会恢复到原始大小。
这是否与scrollView.maximumZoomScale不够大有关?
更正后的代码:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
//imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
imageView.image = selectedImage
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
scrollView.contentMode = .ScaleAspectFit
scrollView.addSubview(imageView)
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleHeight, scaleWidth)
scrollView.minimumZoomScale = 0.3
scrollView.maximumZoomScale = 2.0
scrollView.zoomScale = minScale
centerScrollViewContents()
self.closeBtn.layer.cornerRadius = CGRectGetWidth(self.closeBtn.frame)/20.0
}
最佳答案
在-viewDidLoad()方法中设置框架还为时过早
如果你将在 -viewDidLoad() 中打印你的 scrollView.frame,这实际上会在你的 View 布局它的 subview 之前返回框架。
因此您需要对 imageView 进行约束,或者在 viewWillLayout 中重新定义 imageView.frame。
关于ios - ScrollView 宽高比中的 UIImageView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951205/