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

在iPhone中支持横向和纵向的代码,iphone,Iphone,如何编写支持横向和纵向的代码?我试过这个- (void)setupForOrientation:(UIInterfaceOrientation)orientation { if (UIInterfaceOrientationIsPortrait(orientation)) { CGRect bounds = CGRectMake(0, 0, 768, 1004); scrollView.frame = bounds; // Other vi

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

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

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

我想您想覆盖主视图控制器的
shouldAutorotateToInterfaceOrientation:
方法,以始终返回
YES
。或者您可以在应用程序属性中指定应用程序支持的方向

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

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
        return YES;
}
//此方法将在更改设备方向之前调用,您可以在此方法中设置帧

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

如果您使用过ViewController,那么有几种方法可以替代。首先是

-(BOOL)应自动旋转指向面方向:(UIInterfaceOrientation)到接口方向//覆盖以允许旋转。默认值仅对UIInterfaceOrientationGrait返回YES

您可以在其中指定特定视图是否支持旋转

如果需要根据方向手动配置视图,可以替代以下方法

根据文件

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{
return YES;
}
//旋转开始、到达中间点和结束时通知

-(void)将从接口方向:(ui接口方向)旋转到接口方向持续时间:
(NSTimeInterval)持续时间

要实现您希望实现的功能,您可以对支持的方向返回YES,然后使用第二种方法通过调用[self-setupForOrientation:orientation]相应地配置视图

希望对你有帮助

使用以下代码:

- (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");

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{
return YES;
}
编辑1:p.S.我将肖像视图和景观视图作为两个独立的UIView