[英]Setting contentOffset after zooming and redrawing UIScrollView content
I have a UIScrollView
that contains a view which redraws itself during zooming. 我有一个
UIScrollView
,其中包含一个在缩放过程中会重绘的视图。 The scaling works great, but setting the contentOffset
isn't working. 缩放效果很好,但是设置
contentOffset
无效。 Here is the code 这是代码
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)
}
The result is that content view just expands in the positive x and y direction (down and to the right) when it should be zooming in. I've seen some other potential solutions for scrollViewDidEndZooming
, but even those aren't working for my case. 结果是内容视图在应放大时只会沿正x和y方向(向下和向右)扩展。我已经看到了
scrollViewDidEndZooming
其他一些潜在解决方案 ,但即使对于我的情况也无法使用。 Any idea where I've gone wrong here? 知道我哪里出错了吗?
The problem here was AutoLayout, or rather my use of frames instead of constraints. 这里的问题是AutoLayout,或者我使用框架而不是约束。 The problem was solved by a) creating a width constraint property and then editing its
constant
value when needed, and b) implementing my own zooming behaviour instead of the default UIScrollView
's. 通过以下方法解决了该问题:a)创建宽度约束属性,然后在需要时编辑其
constant
数值,以及b)实现我自己的缩放行为,而不是默认的UIScrollView
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.