如何使用Objective C以编程方式创建设备方向检测?

时间:2016-02-09 04:41:12

标签: ios objective-c iphone device-orientation

我正在尝试完全编程我的iOS应用程序而不使用storyboard。现在我正在努力寻找不同的设备方向Identification。我通过使用设备高度确定了单独的UI大小,但我需要创建不同大小的landscape方向,对于我来说,使用下面的代码我无法处理设备方向。

我的代码如下:

   // Device difrrentiate
    if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) && ((UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)))) {

        // The device is an iPhone or iPod touch.
        CGSize result = [[UIScreen mainScreen] bounds].size;
        if (result.height == 480) {

    // Here I can declare the UI sizes for iPhone 3G & 3GS & 4 & 4S
        }
        if (result.height == 568) {

    // Here I can declare the UI sizes for iPhone 5, 5C & 5S
        }
        if (result.height == 667) {

    // Here I can declare the UI sizes for iPhone 6
        }
        if (result.height == 736) {

           // Here I can declare the UI sizes for iPhone 6 Plus
        }
       }
       } else if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) && ((UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)))) {

        // The device is an iPad and iPad mini running iOS 3.2 or later.
        CGSize result = [[UIScreen mainScreen] bounds].size;
        if (result.height == 1024) {

        // Here I can declare the UI sizes for iPad, iPad 2, iPad Mini
        }
        if (result.height == 2048) {

         // Here I can declare the UI sizes for iPad Air, iPad Mini Retina
        }
     }
 }

1 个答案:

答案 0 :(得分:0)

对于风景,这应该有效:

if(toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation==UIInterfaceOrientationLandscapeRight)

检查一下:

    @interface ViewController ()
    {
        UIButton *btn;
        UIView *vw;
    }
    @end

    @implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor=[UIColor whiteColor];
    btn=[UIButton buttonWithType:UIButtonTypeCustom];
    vw=[[UIView alloc]init];

    btn.frame=CGRectMake(100, 100, 60, 40);
    vw.frame=CGRectMake(100, 360, 150, 100);

    btn.backgroundColor=[UIColor redColor];
    vw.backgroundColor=[UIColor underPageBackgroundColor];
    [self.view addSubview:btn];
    [self.view addSubview:vw];
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation==UIInterfaceOrientationLandscapeRight)
    {
        //in landscape width=480 height=300. statusbar Height=20 by default
        btn.frame=CGRectMake(150, 60, 60, 40);
        vw.frame=CGRectMake(150, 200, 150, 100);
    }
    else
    {
        //in portrait width=320 height=460. statusbar Height=20 by default
        btn.frame=CGRectMake(100, 100, 60, 40);
        vw.frame=CGRectMake(100, 360, 150, 100);
    }
}

希望这有帮助。