对于在IOS中更改方向后保存UIImageView的UIScrollView,布局不正确

时间:2014-01-13 11:19:45

标签: ios ios7 uiscrollview uiimageview uiinterfaceorientation

我设置了一个UIScrollView,其中UIImageView包含UIImage。我加载到图像视图中的UIImage大小约为2300x1200,因为可以缩放而不缩小。

UIScrollView包含一个UIImageView,其设置允许点击/双击以放大和缩小图像。我有followed a tutorial here to create this

示例的源代码可以是downloaded here.

问题
我遇到的问题是改变方向。这些观点不再按预期和抵消的方式展开。

下载图像后(在我的示例中)我完成以下操作:

[self.mainImageView setImage:image];
self.mainImageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image.size};

// Tell the scroll view the size of the contents
self.mainScrollView.contentSize = image.size;

[self setupScales];

然后我按如下方式设置了标尺:

// Set up the minimum & maximum zoom scales
CGRect scrollViewFrame = self.mainScrollView.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / self.mainScrollView.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / self.mainScrollView.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);

self.mainScrollView.minimumZoomScale = minScale;
self.mainScrollView.maximumZoomScale = 1.0f;
self.mainScrollView.zoomScale = minScale;

[self centerScrollViewContents];

然后我将centerScrollViewContents改为:

CGSize boundsSize = self.mainScrollView.bounds.size;
CGRect contentsFrame = self.mainImageView.frame;

if (contentsFrame.size.width < boundsSize.width) {
    contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
    contentsFrame.origin.x = 0.0f;
}

if (contentsFrame.size.height < boundsSize.height) {
    contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
    contentsFrame.origin.y = 0.0f;
}

self.mainImageView.frame = contentsFrame;

使用以下内容设置scrollView和imageView:

self.mainScrollView.translatesAutoresizingMaskIntoConstraints = NO;
self.mainImageView.translatesAutoresizingMaskIntoConstraints = NO;

scrollView对左/右/上/下固定为0的约束,而imageView没有像手动创建的约束。我试图在self.mainScrollView needsUpdateConstraints中运行willRotateToInterfaceOrientation,但这没有任何区别。

在选择第一个选项“图像缩放”然后更改设备的方向时,可以在上面的示例应用程序中复制相同的问题。我不确定什么是错误的,看起来框架设置不正确。我试图在不同的点运行setupScales,但这似乎不会改变问题。

1 个答案:

答案 0 :(得分:0)

当帧发生变化时,似乎会重置scrollView的contentSize。旋转完成后,我必须将其设置回图像大小。

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    // When the orientation is changed the contentSize is reset when the frame changes. Setting this back to the relevant image size
    self.mainScrollView.contentSize = self.mainImageView.image.size;
    // Reset the scales depending on the change of values
    [self setupScales];
}

我已为任何需要此功能的人设置了回购 - https://github.com/StuartMorris0/SPMZoomableUIImageView