因此,我试图通过执行以下操作来强制更改部分代码的设备方向:
if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait ||
[[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown){
[[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationLandscapeLeft animated:NO];
}
但是方向没有改变。为什么是这样?基本上当前方向是纵向的,我希望它被迫处于横向
最佳答案
如果 Inder Kumar Rathore 的建议有效,那就太好了。但是文档将方向属性描述为只读的,所以如果它有效,我不确定你是否可以依赖它在 future 工作(除非 Apple 做了聪明的事情并改变了这一点;强制改变方向,不管如何用户当前正在拿着他们的设备,这是一个明显的功能需求)。
作为替代方案,在 viewDidLoad 中插入的以下代码将成功(并且有点奇怪地)强制定向(假设您已经按照 roronoa zorro 推荐的方式修改了 shouldAutorotateToInterfaceOrientation):
if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]))
{
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *view = [window.subviews objectAtIndex:0];
[view removeFromSuperview];
[window addSubview:view];
}
显然,如果用户当前以纵向模式持有他们的设备(因此推测您的 shouldAutorotateToInterfaceOrientation 仅设置为横向,并且如果用户以纵向模式持有他们的设备,则此例程将其转换为横向)。如果您的 shouldAutorotateToInterfaceOirentation 仅设置为纵向,您只需将 UIDeviceOrientationIsPortrait 与 UIDeviceOrientationIsLandscape 交换。
出于某种原因,从主窗口中删除 View 然后重新添加它会强制它查询 shouldAutorotateToInterfaceOrientation 并正确设置方向。鉴于这不是 Apple 认可的方法,也许人们应该避免使用它,但它对我有用。你的旅费可能会改变。但是这个SO discussion也指其他技术。
关于iphone - 以编程方式将设备方向更改为横向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670834/