iPhone旋转后UIScrollView中的contentOffset

use*_*225 5 uiscrollview uiimageview

我有一个UIImageViewUIScrollView和我有一些麻烦的contentOffset财产.根据Apple的参考,这被定义为:

contentOffset:内容视图的原点偏离滚动视图原点的点.

例如,如果图像位于屏幕的左上角,如下所示,则contentOffset将为(0,0):

   _________
   |IMG    |
   |IMG    |
   |       |
   |       |
   |       |
   |       |
   ---------
Run Code Online (Sandbox Code Playgroud)

对于设备旋转,我有以下设置:

 scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
       UIViewAutoresizingFlexibleHeight);

 imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
       UIViewAutoresizingFlexibleHeight);

 imageView.contentMode = UIViewContentModeCenter;  
    scrollView.contentMode = UIViewContentModeCenter;
Run Code Online (Sandbox Code Playgroud)

这将使一切都围绕屏幕中心旋转.旋转屏幕后,屏幕将如下所示:

    ______________
    |       IMG  |
    |       IMG  |
    |            |
    --------------
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我现在读到contentOffset它,它仍然是(0,0).(如果我在横向模式下移动UIImage,contentOffset则更新值,但它是根据错误的原点计算的.)

有没有办法计算UIImage相对于屏幕左上角的坐标.contentOffset当屏幕处于视图的初始方向时,似乎只返回此值.

我曾尝试阅读self.view.transformscrollView.transform,但他们总是身份.

use*_*225 3

这是执行此操作的一种方法:对于滚动视图集

scrollView.autoresizingMask =(UIViewAutoresizingFlexibleWidth 
                                     | UIViewAutoresizingFlexibleHeight);

scrollView.contentMode = UIViewContentModeTopRight;
Run Code Online (Sandbox Code Playgroud)

即使旋转行为不正确,该UIViewContentModeTopRight模式也会将左上角保持在坐标 (0,0) 处。要获得与 UIViewContentModeCenter 中相同的旋转行为,请添加

    scrollView.contentOffset = fix(sv.contentOffset, currentOrientation, goalOrientation);
Run Code Online (Sandbox Code Playgroud)

进入willAnimateRotationToInterfaceOrientationfix是函数

CGPoint fix(CGPoint offset, UIInterfaceOrientation currentOrientation, UIInterfaceOrientation goalOrientation) {

CGFloat xx = offset.x;
CGFloat yy = offset.y;

CGPoint result;

if (UIInterfaceOrientationIsLandscape(currentOrientation)) {

    if (UIInterfaceOrientationIsLandscape(goalOrientation)) {
        // landscape -> landscape
        result = CGPointMake(xx, yy);
    } else {
        // landscape -> portrait
        result = CGPointMake(xx+80, yy-80);
    }
} else {
    if (UIInterfaceOrientationIsLandscape(goalOrientation)) {
        // portrait -> landscape
        result = CGPointMake(xx-80, yy+80);
    } else {
        // portrait -> portrait
        result = CGPointMake(xx, yy);
    }
}
return result;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将使滚动视图围绕屏幕中心旋转,并确保左上角坐标始终为(0,0)。