在iPhone中支持横向和纵向的代码

时间:2011-12-01 04:30:49

标签: iphone

如何编写支持横向和纵向的代码?我试过这个 -

(void)setupForOrientation:(UIInterfaceOrientation)orientation {
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        CGRect bounds = CGRectMake(0, 0, 768, 1004);
        scrollView.frame = bounds;
        // Other view positioning for portrait.
    } else {
        CGRect bounds = CGRectMake(0, 0, 1024, 748);
        scrollView.frame = bounds;
        // Other view positioning for landscape.
    }
    [self drawBackgroundForOrientation:orientation];
}

但它不起作用。请帮帮我。

4 个答案:

答案 0 :(得分:2)

使用此代码:

- (void)viewDidLoad

    {

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

    }


- (void) orientationChanged:(id)object
{  


 if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight )
 {
 self.view=self.landscapeView;
 NSLog(@"ViewwillAppear= Land");

 }
 else
 {
 self.view = self.portraitView;
 NSLog(@"ViewwillAppear= Port");

 }

无论何时需要定向支持,您都必须为此功能返回“是”。

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{
return YES;
}

编辑1: P.S.我拍了 portraitView& landscapeView 是两个独立的UIView。

答案 1 :(得分:1)

我认为您希望覆盖主视图控制器的shouldAutorotateToInterfaceOrientation:方法,以便始终返回YES。您可以在应用属性中指定应用支持的方向。

答案 2 :(得分:0)

您必须使用以下方法来支持两种方向

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
        return YES;
}

//此方法将在更改设备的方向之前调用,您可以在此方法中设置框架

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
}

答案 3 :(得分:0)

如果您使用过viewcontrollers,那么您可以覆盖一些方法。第一个是

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation; //覆盖以允许轮换。默认值仅对UIInterfaceOrientationPortrait

返回YES

您可以指定特定视图是否支持旋转。

如果您需要根据方向手动配置视图,可以覆盖以下方法

根据文件

此方法的实现应该只根据interfaceOrientation参数中的值返回YES或NO。不要尝试获取interfaceOrientation属性的值或检查UIDevice类报告的方向值。您的视图控制器要么能够支持给定的方向,要么不支持。

//在旋转开始时通知,到达中途点并结束。

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)持续时间;

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;

要实现您希望实现的目标,您可以为支持的方向返回YES,然后使用第二种方法通过调用[self setupForOrientation:orientation]来配置您的视图;

希望它有所帮助!!!