我的应用程序崩溃并显示此消息:
'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'
这是因为我的缩放比例计算为无穷大(除以零)
我正在尝试不使用 Storyboards - 所以一切都是以编程方式完成的。我有两个 ViewController 的
。源 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)
}
关于ios - 滚动期间崩溃,因为边界返回为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51137674/