gpt4 book ai didi

Swift:无法将 ImageView 置于 ScrollView 中心

转载 作者:行者123 更新时间:2023-11-30 10:48:35 28 4
gpt4 key购买 nike

我正在尝试将 X 和 Y 轴中心的 imageView 显示到 scrollView 上,当我运行应用程序时,它很好地适合设备的宽度。我还想平移和缩放imageView。我已经尝试了几乎所有已发布在 SO 上的解决方案,并且也遵循了此 tutorial但不知怎的,它并不能解决我的问题。该图像是从 PDF 生成的。

我以编程方式进行布局。到目前为止我的实现:

let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.backgroundColor = .lightGray
return sv
}()

let imageView: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
return iv
}()

override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self

view.addSubview(scrollView)
scrollView.addSubview(imageView)

NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),

imageView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 10),
imageView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 10),
imageView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -10),
imageView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -10),

])

imageView.image = obtainThumbnail()
}

fileprivate func updateMinZoomScaleForSize(_ size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)

scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}

override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}

func obtainThumbnail() -> UIImage? {
guard let url = Bundle.main.url(forResource: "drawings", withExtension: "pdf") else {return nil}

guard
let data = try? Data(contentsOf: url),
let page = PDFDocument(data: data)?.page(at: 0) else {
return nil
}

let pageSize = page.bounds(for: .mediaBox)
return page.thumbnail(of: CGSize(width: pageSize.width, height: pageSize.height), for: .mediaBox)
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}

这是我运行应用程序时想要的结果。 enter image description here

这是我现在运行应用程序时的结果,过度拉伸(stretch)。 enter image description here

有人可以告诉我我错过了什么吗?

最佳答案

我认为 View 是在 UIViewController 中延迟加载的,因此在 UI 生命周期的后期进行计算应该可以解决问题。删除 viewWillLayoutSubviews 中的调用并改为使用:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

updateMinZoomScaleForSize(view.bounds.size)
}

似乎有效。

关于Swift:无法将 ImageView 置于 ScrollView 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195648/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com