问答-如何强制设备方向在横向和纵向之间旋转

阿尔伯特·伦肖

我现在以问答形式发布,因为目前在 S / O 上有一些帖子,涉及类似的问题和答案,并非对所有用例 都完全正确它们通常足以满足OP的一个特定用例,但对来网站寻求通用 答案的 人们不利,正如我刚刚经历的 那样,这会导致数小时的调试工作受挫(并且这样做是通过遍历StackOverflow的所有资源来发现, 除了在其他帖子上的评论之外,没有在任何地方正式询问过这个问题(及其答案))。


问:如何强制我的应用随意在纵向和横向模式之间切换?

尽管有许多小片段允许这样做,但是它们以各种无法预见的方式失败了。

例如:

1)您可以旋转屏幕UI(而不是设备方向),但是如果您截图或显示iOS本机内容(如弹出警报),则它们的方向将错误。

2)如果您将orientation按键设置为所需的方向,则UI并不总是在之后(或根本没有)立即自动更新。

3)如果您只是手动执行此操作并手动更新UI,则其他VC可能仍会篡改w /方向,因此不会被“锁定”。

4)如果您手动更新设备方向并刷新UI,则由于UI尚未更新设备设置,因此添加新的ViewController.view的宽度和高度将被翻转,您必须等待未知的时间(介于0和1秒),以便在更新这些属性(UIDevice的尺寸)之前完成旋转动画。

等等。

我在下面的回答解决了在搜索各种SO线程时发现的所有潜在问题。

阿尔伯特·伦肖

A:

添加到AppDelegate.h

@property () BOOL landscape;

添加到AppDelegate.m

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.landscape) {
        return UIInterfaceOrientationMaskLandscapeRight;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}


-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    if (self.landscape) {
        return UIInterfaceOrientationLandscapeRight;
    } else {
        return UIInterfaceOrientationPortrait;
    }
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if (self.landscape) {
        return (UIInterfaceOrientationLandscapeRight);
    } else {
        return (UIInterfaceOrientationPortrait);
    }
}

-(NSUInteger)supportedInterfaceOrientations {
    if (self.landscape) {
        return UIInterfaceOrientationLandscapeRight;
    } else {
        return UIInterfaceOrientationPortrait;
    }
}

-(BOOL)shouldAutorotate {
    return NO;
}

添加到您的VC.m

-(void)setLandscape:(BOOL)landscape {
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.landscape = landscape;
    
    if (landscape) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    } else {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }
    
    [UINavigationController attemptRotationToDeviceOrientation];//THIS IS THE MOST IMPORTANT LINE IN HERE AND EVERYONE AND ALL SAMPLE CODE LEAVES IT OUT FOR SOME REASON, DO NOT REMOVE THIS LINE. (Forces UI to update), otherwise this orientation change will randomly fail around 1% of the time as UI doesn't refresh for various unknown reasons.
    
}

最重要的一行是[UINavigationController attemptRotationToDeviceOrientation];出于某种原因,网络上的每个人,stackoverflow,示例代码等都遗漏了。仅设置orientation密钥将导致它在98%的时间内都能正常工作,但是随机UI不会更新,或者会在设置密钥之前更新,并且您会遇到方向错误,这会迫使它在需要时进行更新。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章