iOS -shouldautorotatetointerfaceorientation 自動旋轉畫面

使用iPhone、iPad、iPod Touch系列產品常常很自然的會把他轉來轉去(如下圖)

圖片來源:http://www.sopods.com/images/apps/FullScreenIPhone_rotation_bars.jpg

根據官方文件(Launching your Application in Landscape)使用起來確實超級簡單(此方法使用於iOS 2.1以後版本)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


就這樣短短幾行就可以把畫面固定在橫的
Home鍵在右手邊
那如果要轉其他邊或者瘋狂的隨你轉呢
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
NSLog(@"shouldAutorotateToInterfaceOrientation = %d",interfaceOrientation);

if(interfaceOrientation == UIInterfaceOrientationLandscapeRight){
NSLog(@"RIGHT");
//return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft){
NSLog(@"LEFT");
//return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

if(interfaceOrientation == UIInterfaceOrientationPortrait){
NSLog(@"Portrait");
//return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

if(interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
NSLog(@"PortraitUpsideDown");
//return (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}
return YES;
}


僅只需要將最後的return設定為YES畫面就會隨著你轉
想要固定在某一邊只需要改成return下面這幾個
上:UIInterfaceOrientationPortraitUpsideDown
下:UIInterfaceOrientationPortrait
左:UIInterfaceOrientationLandscapeLeft
右:UIInterfaceOrientationLandscapeRight

而我在這function內最上面所印出來的log最後面帶的數字就是代表這方向的數字
想要使用只需要將這function加入在.m檔中的@implementation與@end中間
但.h檔必須繼承UIViewController

光是能轉換還是會遇上座標的問題
如果本來所使用都是固定座標就必須把座標系轉換一下(如下圖)

圖片來源:http://blog.sallarp.com/shouldautorotatetointerfaceorientation/



參考連結
iOS Developer Library
iOS Developer Library - UIApplication Class Reference
iOS Developer Library - Technical Note TN2244 Launching your Application in Landscape
http://blog.sallarp.com/shouldautorotatetointerfaceorientation/

沒有留言:

張貼留言