旋转UIView时覆盖layoutSubviews

时间:2010-10-29 11:43:01

标签: iphone objective-c uiview ios4 layoutsubviews

在UIView内旋转滚动视图时,滚动视图无法使用其默认的自动调整行为正确定位。

因此,当轮换发生时,在willRotateToInterfaceOrientation我呼叫[self.view setNeedsLayout];,我的layoutSubviews方法如下:

- (void)layoutSubviews {
    NSLog(@"here in layoutSubviews");
}

但是在方法上设置一个断点,它似乎永远不会进入方法。

我是否需要做其他事情才能让它发挥作用?

感谢。

5 个答案:

答案 0 :(得分:3)

将在更改方向之前调用willRotateToInterfaceOrientation,因此您的UIView仍将具有旧的大小。 请尝试使用didRotateFromInterfaceOrientation。

另外,为了增加效果,我会在willRotateToInterfaceOrientation中隐藏scrollView(可能在UIAnimation块内部),调整它的大小,然后在didRotateFromInterfaceOrientation中显示它(再次,可能在动画块内)。

以下是我的某个应用的摘录:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
self.myScroll.hidden = YES;
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView commitAnimations];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
self.myScroll.hidden = NO;
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView commitAnimations];
}

您甚至可以通过使用UIInterfaceOrientationIsPortrait(orientation)或UIInterfaceOrientationIsLandscape(orientation)检查新方向来执行奇特的操作。

答案 1 :(得分:2)

如果未调整视图大小或移动视图,则调用[someScrollView setNeedsLayout]实际上可能无法执行任何操作。正如您所说,永远不会使用默认的自动调整行为调用该方法,因为默认行为是根本不调整大小。您最有可能需要设置someScrollView.autoresizingMask。当界面旋转时,视图将自行调整大小,layoutSubviews将被调用。

答案 2 :(得分:0)

实际上,您可能希望覆盖视图控制器willAnimateRotationToInterfaceOrientation:duration:方法(从我的示例中删除):

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                        duration:(NSTimeInterval)duration {
    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
        boardView.frame = CGRectMake(0, 0, 320, 320);
        buttonsView.frame = CGRectMake(0, 320, 320, 140);
    } else {
        boardView.frame = CGRectMake(0, 0, 300, 300);
        buttonsView.frame = CGRectMake(300, 0, 180, 300);        
    }

}

答案 3 :(得分:0)

该方法无法调用,因为ViewController没有layoutSubviews方法。

当您致电[self.view setNeedsLayout];时,它只会调用视图控制器视图的layoutSubviews方法:[self.view layoutSubviews]

您需要创建UIScrollview的子类才能使其正常工作。

答案 4 :(得分:0)

您应该覆盖willAnimate ...并设置视图的新框架。应该在轮换期间自动调用Layoutsubviews。

相关问题