iPhone中的自动定位

时间:2011-09-12 05:19:25

标签: iphone objective-c orientation

我使用UIDeviceOrientationDidChangeNotification来获取有关landscape和potrait模式的通知。在我的项目中,我需要相应地更改放置在UIControls上的UIView的位置。我是否必须手动更改每个UIControl的帧大小,因为这是忙碌的?

2 个答案:

答案 0 :(得分:1)

在视图控制器中,您应该实现方法:

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

此方法应返回YES以获得支持的方向。

如果您希望子视图自动调整大小并重新定位,那么您应该设置该视图的相应属性autoresizingMask。例如:

blackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight |
                                 UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | 
                                 UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;

答案 1 :(得分:0)

您确实需要使用shouldAutorotateToInterfaceOrientation ...方法,但是在它正常工作之前您需要做一些事情。首先,您需要两个xib文件,一个用于横向,另一个用于纵向。然后,您需要使用这样的函数:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft){
    //prepare for a Landscape view
    }
else{
    //prepare for a portrait view
    }
    return YES;
}

至于准备横向或纵向视图,使用自动调整可以工作,但您可能需要完全独立的xib。我找不到在活动视图控制器中更改xib的方法,因此我建议创建一个视图控制器的单独实例。例如:

当您展示viewController的第一个实例时,请使用纵向xib呈现它。您可能还需要一个布尔值来跟踪当前的xib。然后实现此代码:

/*Assuming you are using a viewcontroller called viewController, and you have a boolean called xibPortrait.
You have presented this view controller using the portrait xib.
You also have a landscape xib, Landscape.xib
*/

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ((interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft) && xibPortrait){
        xibPortrait = FALSE;
        viewController *Land = [[ViewController alloc] initWithNibName:@"Landscape" bundle:nil];
        [self presentModalViewController:Land animated:NO];
        [Land release];
    }
else if(!xibPortrait){
    [self.parentViewController dismissModalViewControllerAnimated:NO];
    xibPortrait = TRUE;
    }
return YES;
}


//This should work but if you can, you should try to use Autoresizing.

编辑: 我也发现了有人在我的一个问题上发帖。与使用上述方法相比,它可以帮助您的应用更有效地工作: http://aseriesoftubes.com/articles/ipad-development-101-orientation/