手动设置界面方向

4
有没有简单的方法手动设置界面方向? 在加载时,我需要将界面设置为纵向,即使设备方向可能为横向。 希望能避免使用CGAffineTransforms。
3个回答

16

我知道的一种方法(有点hack,可以在更改为所需方向之前显示一个方向)是:

- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];

    UIApplication* application = [UIApplication sharedApplication];

    if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
    {
        UIViewController *c = [[UIViewController alloc]init];
        [self presentModalViewController:c animated:NO];
        [self dismissModalViewControllerAnimated:NO];
        [c release];
    }
}

这对我描述的情况实际上非常有效。但是出于某种原因,尝试从纵向模式强制切换到横向模式(将UIInterfaceOrientationPortrait更改为UIInterfaceOrientationLandscapeLeft)时效果不佳。有什么想法吗? - brad_roush
我不知道,丹,你需要自己尝试一下,通过创建一个子类化的UIViewController,在“shouldAutorotateToInterfaceOrientation:”方法中只处理横向。 - Shane Powell
@ShanePowell,你的代码在iOS6之前运行得很好。在iOS6中有没有类似的技巧? - Ananth

2

在加载之前,重写此方法以控制方向...

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation

是的,你说得对。我的错误。我更新了我的答案。你可以考虑只覆盖 shouldAutorotateToInterfaceOrientation 方法并保持方向,只要你需要。 - Saran

2

首先,将您的应用程序和视图设置为仅支持纵向模式,然后使用我从我的重构库 es_ios_utils 中获取的此类别方法:

@interface UIViewController(ESUtils)
    // Forces without using a private api.
    -(void)forcePortrait;
@end

@implementation UIViewController(ESUtils)

-(void)forcePortrait
{
    //force portrait orientation without private methods.
    UIViewController *c = [[UIViewController alloc] init];
    [self presentModalViewController:c animated:NO];
    [self dismissModalViewControllerAnimated:NO];
    [c release];
}

@end

在帧完成之前被关闭的视图将不会显示。


我可能从Shane那里或他的源获取了这个。他的更完整,而我的建议是使用类别进行重复使用。 - Peter DeWeese
竖屏是未扩展UIViewController的默认支持方向,呈现它将强制使用有效的方向。 - Peter DeWeese

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接