我的应用程序崩溃,并显示以下消息:
“ CALayerInvalidGeometry”,原因:“ CALayer位置包含NaN:[nan nan]”
这是因为我的缩放比例被计算为无穷大(除以零)
我正在尝试不使用演示图板的情况-因此所有操作均以编程方式完成。我有两个ViewController's
。源ViewController
将新的ViewController
推入堆栈,如下所示:
..
let destinationVC = DetailViewController()
destinationVC.setWith(img: photo)
navigationController?.pushViewController(destinationVC, animated: true)
...
现在,当我缩小destinationVC
时,我的scrollView
崩溃了。这是因为在updateMinZoomScaleForSize
中,bounds
返回的是0。我尝试在其他一些地方调用此函数:
viewDidLayoutSubviews
-仍然崩溃viewWillLayoutSubviews
-仍然崩溃viewWillAppear
-仍然崩溃viewDidAppear
-不会崩溃,但是图像会“跳”到位我也尝试过使用image.setNeedsDisplay()
方法调用image.setNeedsLayout
和setWith(img: UIImage)
,但是我仍然观察到相同的结果。
这是我的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
}
答案 0 :(得分:1)
设置.image
的{{1}}属性不会改变UIImageView
的框架。
尝试将您的UIImageView
函数更改为此:
setWith()