iPhone旋转后UIScrollView中的contentOffset

5

我在一个UIScrollView中有一个UIImageView,并且我在contentOffset属性上遇到了一些问题。根据苹果的参考文献,这被定义为:

contentOffset: 内容视图的原点相对于滚动视图的原点的偏移量。

例如,如果像下面这样的图片位于屏幕左上角,则contentOffset将会是(0,0):

   _________
   |IMG    |
   |IMG    |
   |       |
   |       |
   |       |
   |       |
   ---------

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

 scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
       UIViewAutoresizingFlexibleHeight);

 imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
       UIViewAutoresizingFlexibleHeight);

 imageView.contentMode = UIViewContentModeCenter;  
    scrollView.contentMode = UIViewContentModeCenter;

这将使所有内容围绕屏幕中心旋转。 旋转屏幕后,屏幕将如下所示:

    ______________
    |       IMG  |
    |       IMG  |
    |            |
    --------------

我的问题是,如果我现在读取contentOffset,它仍然是(0,0)。(如果我在横向模式下移动UIImage,则contentOffset的值会更新,但是它是相对于错误的原点计算的。)
是否有一种方法可以计算UIImage相对于屏幕左上角的坐标。contentOffset似乎只在视图的初始方向下返回此值。
我尝试过读取self.view.transformscrollView.transform,但它们始终是恒等变换。
1个回答

3
这里有一种方法可以实现这个功能:对于scrollview,设置

scrollView.autoresizingMask =(UIViewAutoresizingFlexibleWidth 
                                     | UIViewAutoresizingFlexibleHeight);

scrollView.contentMode = UIViewContentModeTopRight;

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

    scrollView.contentOffset = fix(sv.contentOffset, currentOrientation, goalOrientation);

willAnimateRotationToInterfaceOrientation函数中的内容进行修复。 fix是该函数的功能。

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;
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接