在缩放和重绘UIScrollView内容后设置contentOffset

时间:2016-02-09 00:37:41

标签: ios swift uiscrollview

我有一个UIScrollView,其中包含一个在缩放过程中重绘的视图。缩放效果很好,但设置contentOffset不起作用。这是代码

func scrollViewDidZoom(scrollView: UIScrollView) {

    // Get relative position of content view
    let pX = (scrollView.contentOffset.x + scrollView.frame.width / 2.0) / scrollView.contentSize.width
    let pY = (scrollView.contentOffset.y + scrollView.frame.height / 2.0) / scrollView.contentSize.height

    // Rescale and redraw content view        
    contentView.frame=CGRect(x: 0,
        y: 0,
        width: contentView.frame.width * scrollView.zoomScale,
        height: contentView.frame.height * scrollView.zoomScale)
    contentView.scale *= scrollView.zoomScale
    contentView.setNeedsDisplay()

    // Recalculate content offsets so that relative position of content is the same as before
    let nX = contentView.frame.width * pX - scrollView.frame.width / 2.0
    let nY = contentView.frame.height * pY - scrollView.frame.height / 2.0

    // Reset zoom level of scroll view and content offsets
    scrollView.setZoomScale(1.0, animated: false)
    scrollView.setContentOffset(CGPoint(x: nX, y: nY), animated: false)
}

结果是,当内容视图应该放大时,内容视图只会在正x和y方向(向下和向右)展开。我已经看到scrollViewDidEndZooming的其他potential solutions,但即便是那些不适合我的情况。知道我哪里出错吗?

1 个答案:

答案 0 :(得分:0)

这里的问题是AutoLayout,或者说我使用的是框架而不是约束。该问题通过以下方法解决:a)创建宽度约束属性,然后在需要时编辑其constant值,以及b)实现我自己的缩放行为而不是默认的UIScrollView