滚动时崩溃,因为边界返回为零

时间:2018-07-02 13:45:01

标签: ios swift uiscrollview

我的应用程序崩溃,并显示以下消息:

  

“ 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。我尝试在其他一些地方调用此函数:

  1. viewDidLayoutSubviews-仍然崩溃
  2. viewWillLayoutSubviews-仍然崩溃
  3. viewWillAppear-仍然崩溃
  4. viewDidAppear-不会崩溃,但是图像会“跳”到位

我也尝试过使用image.setNeedsDisplay()方法调用image.setNeedsLayoutsetWith(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
}

1 个答案:

答案 0 :(得分:1)

设置.image的{​​{1}}属性不会改变UIImageView的框架。

尝试将您的UIImageView函数更改为此:

setWith()