2

我有一个 iPad 项目的结构如下: - AppDelegate - MainWindow - 视图控制器 - 视图

View Controllers .m 文件以编程方式加载另一个视图并将其放置在屏幕上。这个视图将被滑入和滑出。

我这样做:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect  viewRect = CGRectMake(0, 0, 0, 0);
    CalculatorView *v = [[[CalculatorView alloc] 
                                    initWithFrame:viewRect] autorelease];
    [self.view.window addSubview:v];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    v.view.frame   = CGRectMake(0, 0, 460, 320);
    [UIView commitAnimations];
}

我遇到的问题是我在这里添加的子视图似乎没有正确的方向。该项目仅支持景观,并启动景观。容器视图很好,它包含一些也很好的按钮。然而,这个以编程方式加载的视图卡在纵向模式下。我提供了以下自动旋转代码(在加载的视图的 .m 中):

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

但它永远不会被调用。

那么,如何让以编程方式添加的子视图以横向而不是纵向模式加载?蒂亚!

4

1 回答 1

1

UIView 类不接收方向更改消息。

(特别是shouldAutorotateToInterfaceOrientation方法,它是一个 UIViewController 方法)

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006926-CH3-SW23

您必须在视图中手动添加一个方法来通知它方向已更改,并且您应该在控制器方法中调用此shouldAutorotateToInterfaceOrientation方法。

为此,您必须在控制器中创建对视图的引用并自己处理内存。

@interface MyController : UIViewController {

   CalculatorView *_calculatorView;

}

@end

@implementation MyController


- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect  viewRect = CGRectMake(0, 0, 0, 0);

   //inits _calculatorView without the autorelease. Will be released in the dealloc method
    _calculatorView = [[CalculatorView alloc] 
                                    initWithFrame:viewRect];
    [self.view.window addSubview:v];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    _calculatorView.view.frame   = CGRectMake(0, 0, 460, 320);
    [UIView commitAnimations];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   //calls custom interface orientation method
   [_calculatorView MyInterfaceChangedCustomMethod:interfaceOrientation];

    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

-(void) dealloc { 

   [_calculatorView release];
   [super dealloc];
}



@end

编辑:如果您的 CalculatorView 很简单,并且您只需要在设备旋转后正确更改其框架,我认为最好的方法是使用类似于以下视图的 autoresizingMask

_calculatorView = [[CalculatorView alloc] 
                                    initWithFrame:viewRect];
_calculatorView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
于 2011-05-11T01:29:56.750 回答