如何以编程方式设置设备(UI)方向?

Sam*_*man 23 iphone objective-c orientation ios

希望屏幕上的所有内容(UI)能够从左到右旋转或反之亦然.

我该怎么做呢?这是私人的吗?

我知道

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {}
Run Code Online (Sandbox Code Playgroud)

让你说出UI可以有哪些方向,但有没有办法一次只强制一个?

干杯

UIB*_*der 24

在iOS [[UIDevice currentDevice] setDeviceOrientation:UIDeviceOrientationSomeOrientation]方法中缺席.但我们可以使用状态栏旋转视图,为此:

- (void)showAlbum {
    // check current orientation
    if ([[UIApplication sharedApplication] statusBarOrientation] != UIInterfaceOrientationLandscapeLeft) {
        // no, the orientation is wrong, we must rotate the UI
        self.navigationController.view.userInteractionEnabled = NO;
        [UIView beginAnimations:@"newAlbum" context:NULL];
        [UIView setAnimationDelegate:self];
        // when rotation is done, we can add new views, because UI orientation is OK
        [UIView setAnimationDidStopSelector:@selector(addAlbum)];
        // setup status bar
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft  animated:NO];
        // rotate main view, in this sample the view of navigation controller is the root view in main window
        [self.navigationController.view setTransform: CGAffineTransformMakeRotation(M_PI / 2)];
        // set size of view
        [self.navigationController.view setFrame:CGRectMake(0, 0, 748, 1024)];
        [UIView commitAnimations];
    } else {
        [self addAlbum];
    }

}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 18

我在这方面取得了成功:

 if (self.interfaceOrientation != UIInterfaceOrientationPortrait) {
    // http://stackoverflow.com/questions/181780/is-there-a-documented-way-to-set-the-iphone-orientation
    // http://openradar.appspot.com/radar?id=697
    // [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait]; // Using the following code to get around apple's static analysis...
    [[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:") withObject:(id)UIInterfaceOrientationPortrait];
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用以下命令克服ARC问题:`[[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:")withObject:(__ bridge id)((void*)UIInterfaceOrientationPortrait)];`但它无论如何都不能在iOS6下工作. (4认同)
  • 以上代码不会在ARC下编译.它并不欣赏从NSInteger到id的演员表.但是,您可以使用NSInvocation.也就是说,它在iOS 6下对我不起作用. (3认同)

tob*_*byc 16

调用该方法来确定您的界面是否应该自动旋转到给定的旋转(即让UIKit执行艰苦的工作,而不是手动执行).

因此,如果您希望您的应用仅在横向工作,您可以使用以下方法实现该方法的主体:

return UIInterfaceOrientationIsLandscape(interfaceOrientation);

如果您希望您的UI自动旋转到所有方向,您可以 return YES;

那是你问的吗?


Jus*_*ers 5

如果您提供一个模态视图控制器,它实现-shouldAutorotateToInterfaceOrientation:只支持一个方向,整个界面将自动强制进入它.我不认为有一种方法可以以编程方式改变方向.