![](/img/trans.png)
[英]Force iOS ViewController to rotate to device orientation after unlocking programmatic rotation lock
[英]Force device rotation with +attemptRotationToDeviceOrientation failing
根據這里的UIViewController
文檔,
使用[UIViewController attemptRotationToDeviceOrientation]
強制系統嘗試將接口旋轉到新方向。 我試圖通過以下方式強制界面從縱向旋轉到橫向:
forceLandscape
標志 [UIViewController attemptRotationToDeviceOrientation]
-supportedInterfaceOrientations
並檢查標志以更改支持的方向,例如 這會強制再次調用-supportedInterfaceOrientations
,看起來像
- (NSUInteger)supportedInterfaceOrientations {
return self.forceLandscape ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskPortrait;
}
即使正在調用-supportedInterfaceOrientations
並返回新方向,接口也不會旋轉。 我已經確認該項目允許所有方向,並且該視圖控制器是窗口的根視圖控制器。 有沒有其他人遇到這個問題並找到了解決方案? 我知道所有修復這個問題(提出和解雇模態等),但如果可能的話,我想要一個干凈的解決方案。 我已在iOS 6和7上驗證了此問題。
以下是重現的完整代碼:
@interface ALTViewController ()
@property (nonatomic, assign) BOOL forceLandscape;
@end
@implementation ALTViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.forceLandscape = NO;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"button" forState:UIControlStateNormal];
[button sizeToFit];
[self.view addSubview:button];
button.center = self.view.center;
[button addTarget:self
action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonPressed:(id)sender
{
self.forceLandscape = YES;
[UIViewController attemptRotationToDeviceOrientation];
}
- (NSUInteger)supportedInterfaceOrientations
{
return self.forceLandscape ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskPortrait;
}
調用attemptRotationToDeviceOrientation僅旋轉接口的方向,當且僅當設備本身已旋轉時。
例如,如果視圖控制器僅支持縱向方向,並且用戶將設備旋轉到橫向,則不會發生界面旋轉。 當設備處於橫向時,讓我們說你的代碼切換一個允許橫向方向的標志。 接口方向會發生什么? 沒什么,因為已經發生了設備方向。 要使接口方向與設備方向匹配,您需要調用attemptRotationToDeviceOrientation。
在我自己的代碼中,我最近創建了一個自定義的多部分視圖動畫,如果界面旋轉發生在它的中間,它看起來不正確。 所以我在簡短的動畫期間關閉了界面旋轉。 如果用戶在動畫期間旋轉設備,則不會發生界面方向。 但是,當重新打開界面方向時,在我調用attemptRotationToDeviceOrientation之前,界面不會旋轉以匹配設備方向。
您可以嘗試使用以下內容實現:setStatusBarOrientation:animated: https : //developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/ setStatusBarOrientation:animated :
這對我來說也是一個類似的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.