iOS 強制轉成橫屏的方式

手裏的項目需要在豎屏的情況下有個別頁面進行橫屏強制切換,困擾了一天終於找到解決的辦法。辦法由如下兩個:

(1)手動改變view.transform屬性

簡明的說就是旋轉你的view,將view旋轉後強迫用戶進行橫屏操作

self.view.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width);
先設置一個橫屏狀態的view 接下來在添加你要的控件

接下來就是將你的view進行旋轉了,代碼如下:

self.view.center = CGPointMake([[UIScreen mainScreen] bounds].size.width/2, [[UIScreen mainScreen] bounds].size.height/2);
    CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
    [self.view setTransform:transform];

好了,現在可以看到你的view大致已經達到了你想要的結果,如果你是隱藏狀態欄,如果你的uiview中存在UItextfield你會發現你的鍵盤還是從豎屏狀態出現,鍵盤的方向跟狀態欄有關,修改你的狀態欄方向即可

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
在實際操作過程中 我發現一個問題:在橫屏界面退至後臺再進入前臺會發現界面又旋轉了90...看了半天不知道問題在哪裏,估計是狀態欄的原因,我用了第二種方法

(2)通過setOrientation:強制旋轉到一個特定的方向

網上看了下,Apple在3.0後不支持此方法了,已經成爲私有方法了,要跳過App Store的審覈有個巧妙的方法:

if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationLandscapeRight;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
但是要在子試圖中重寫下面幾個方法:

-(BOOL)shouldAutorotate {
    
    NSLog(@"UINavigationController 100");
    // 不想其子頁面支持旋轉, 可直接返回 NO
    return YES;
}
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeRight;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return toInterfaceOrientation==UIInterfaceOrientationLandscapeRight;
}

但是如果第一種方法就能滿足你最好就用第一種,因爲第二種畢竟存在一定的風險

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章