我的应用程序崩溃并显示以下消息:
"CALayerInvalidGeometry",理由:"CALayer 位置包含 NaN:[nan nan]">
这是因为我的缩放比例计算为无穷大(除以零(
我正在尝试不使用故事板 - 所以一切都以编程方式完成。我有两个ViewController's
.源ViewController
将新ViewController
推送到堆栈上,如下所示:
..
let destinationVC = DetailViewController()
destinationVC.setWith(img: photo)
navigationController?.pushViewController(destinationVC, animated: true)
...
现在,当我缩小scrollView
时,我的destinationVC
崩溃了。这是因为在updateMinZoomScaleForSize
中,bounds
返回为 0。我尝试在其他几个地方调用此函数:
viewDidLayoutSubviews
- 仍然崩溃viewWillLayoutSubviews
- 仍然崩溃viewWillAppear
- 仍然崩溃viewDidAppear
- 没有崩溃,但图像"跳"到位
我也尝试在setWith(img: UIImage)
方法中调用image.setNeedsDisplay()
和image.setNeedsLayout
,但我仍然观察到相同的结果。
这是我destinationVC
的完整代码
private let image : UIImageView = {
let img = UIImageView()
img.translatesAutoresizingMaskIntoConstraints = false
img.contentMode = .scaleAspectFit
return img
}()
private lazy var scrollView : UIScrollView! = {
let scroll = UIScrollView(frame: view.bounds)
scroll.contentSize = image.bounds.size
scroll.translatesAutoresizingMaskIntoConstraints = false
return scroll
}()
func setWith(img: UIImage) {
self.image.image = img
image.setNeedsDisplay()
image.setNeedsLayout()
updateMinZoomScaleForSize(view.bounds.size)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
/// Add scrollview
view.addSubview(scrollView)
scrollView.addSubview(image)
scrollView.delegate = self
addScrollViewConstraints()
addImageConstraints()
}
private func addScrollViewConstraints() {
let margins = view.safeAreaLayoutGuide
scrollView.leftAnchor.constraint(equalTo: margins.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: margins.rightAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
}
private func addImageConstraints() {
image.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
image.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
image.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
image.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return image
}
private func updateMinZoomScaleForSize(_ size: CGSize) {
print(image.bounds.width)
let widthScale = size.width / image.bounds.width
let heightScale = size.height / image.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
设置UIImageView
的.image
属性不会更改UIImageView
的框架。
尝试将setWith()
函数更改为以下内容:
func setWith(img: UIImage) {
self.image.image = img
image.frame.size = img.size
updateMinZoomScaleForSize(view.bounds.size)
}