根据设备(iPhone或iPad)不同设定不同的设备方向

12

我正在进行一个通用项目,需要满足以下要求:

  • 对于iPhone,只允许纵向方向。
  • 对于iPad,只允许横向方向。

如何在(Swift)中实现?


2
你尝试过在Xcode中使用info.plist吗? - ScarletMerlin
嗨@ScarletMerlin。谢谢你的建议。我不知道我怎么错过了“支持的界面方向(iPad)”这个关键字。使用这个关键字,它可以按照要求工作。请随意创建一个答案,这样我就可以点赞了。干杯,伙计。 - insetoman
1
不用担心,我不需要来自批准答案的积分。info.plist 是告诉 iPhone 如何处理全局设置的方式。你也可以在代码中完成它,但这几乎从未被推荐过。 - ScarletMerlin
2个回答

45

根据@ScarletMerlin的建议,我认为更改info.plist中的键是我需要满足要求的最佳解决方案(每种设备都有固定的方向类型)。

这是我使用的设置截图。也许它可以帮助其他有类似疑问的开发者。

设置在info.plist文件中

相关源代码如下:

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>

1
这会覆盖目标 > 通用 > 部署信息 > 设备方向下的任何选项吗? - user5306470

0

我的建议是检查您的应用程序运行的硬件。为此,请使用以下代码行。

if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)

然后,一旦您检测到硬件,使用shouldAutorotateToInterfaceOrientation:来阻止方向变化:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    return UIInterfaceOrientationIsLandscape(orientation);
}

举个例子,你可以这样做

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation
    {
        if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) 
            return UIInterfaceOrientationIsLandscape(orientation); // If iPad
        else
            return UIInterfaceOrientationIsPortrait(orientation); // Else, it is an iPhone
    }

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