如何避免ViewController打开时Orientation错误

本文讨论了在iPad项目中实现BeginnerGuide的策略,包括使用SplitViewController和如何解决在ViewWillAppear中弹出窗口初始总是Portrait模式的问题。通过引入延迟或使用Block,确保窗口显示时与设备当前模式一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在一个iPad项目上要做一个BeginnerGuide,我的设计是将其做在help里,在第一次运行程序时显示此help,否则在需要了解帮助信息时,可以点击help按钮打开此BeginnerGuide。

我的结构是一个基于SplitViewController的Master-Detail结构,在第一次运行时,在Master的ViewWillAppear中通过performSegueWithIdentifier弹出此help窗口,其它情况下通过在点击Master中的help按钮弹出。之所以在ViewWillAppear中弹出而不是ViewDidAppear,是由于不想在显示BeginnerGuide之前,让用户看到主界面,那样就不叫BeginnerGuide了。

这里的问题是,在ViewWillAppear中弹出的窗口初始时总是Portrait模式,而不管设备所处模式是什么。但是打开之后,旋转设备,窗口则可以根据实际的模式调整过来。如果在父窗口的ViewWillAppear或新弹出的ViewController中的ViewDidLoad中运行如下代码:

    if  (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
    {
        //landscape view code
        NSLog(@"Landscape");
    }
    else
    {
        //portrait view code
        NSLog(@"Portrait");
    }
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
        // portrait
        NSLog(@"Portrait");
    } else {
        // landscape
        NSLog(@"Landscape");
    }
    
    if  (UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation]))
    {
        //landscape view code
        NSLog(@"Landscape");
        
    }
    else
    {
        //portrait view code
        NSLog(@"Portrait");
    }

当设备为Landscape模式时,实际输出为:

Portrait
Portrait
Landscape

也就是视图所处模式与设备是不同的。

遍寻Baidu、Google、StackOverFlow,唯一的收获是,在ViewWillAppear中,无法知道正确的Orientation信息。不过幸运的是,我最后找到了这篇文章,文中说,设备的消息已经传到了程序,刚才的例子也可以说明这点,由于Rotate消息在ViewWillAppear之前就已经排在消息队列中,这个队列是用于处理所有启动过程(Startup process)的,我们的程序只是晚了一点点,当我们的ViewController显示的时候,Rotate消息已经处理结束了。

解决方案其实很简单,我们无法将我们的显示提前到Startup Process中,但是可以延后,等到Startup Process处理完成,比如增加一个timer延时,或者更简单的方案--使用Block,代码如下:

- (void)viewWillAppear: (BOOL)animated {
    [super viewWillAppear:animated];
    if (freshInstall) {
        dispatch_async(dispatch_get_main_queue(),^{
            [self performSegueWithIdentifier: @"firstRun" sender: self];
        });
    }
}

这篇Twitter说,这个问题已经在iOS6上解决了。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值