ScrollView 宽高比中的 UIImageView 不起作用

UIImageView in ScrollView aspect ratio not working

我在我的故事板中定义了一个 UIScrollView,带有一个插座。这个滚动视图通过代码(不在故事板上)添加了一个 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 这实际上会 return 在你的视图布局它的子视图之前的框架。

因此您需要对 imageView 进行约束或在 viewWillLayout 中重新定义 imageView.frame。