標籤:style blog http color io os ar for sp
iPhone和iPad裝置有4個方向的狀態,我們可以針對應用當前所處的方向調整介面。
為了使應用支援不同的方向,首先我們需要在項目設定中設定裝置支援的方向(也可以在項目的plist中設定)
Portrait 豎放,home鍵在螢幕下方
Upside Down 豎放,home鍵在螢幕上方
Landscape Left 橫放,home鍵在螢幕左方
Landscape Right 橫放,home鍵在螢幕右方
我們在StoryBoard中拖入一個新的ViewController,綁定好它的File‘s Owner,然後放入6個UIView,設定好不同的背景色
程式運行後,我們在旋轉模擬器,發現在豎屏和橫屏狀態下,介面顯示如下
顯然橫屏狀態下這樣的顯示是不適合的,為了得到合適的顯示效果,我們需要在ViewController中寫一些代碼。
首先我們先看一下在ViewController中和重力感應相關的一些函數
- (BOOL)shouldAutorotate
此函數返回YES表示此視圖控制器支援重力感應,返回NO表示此視圖控制器不支援重力感應
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
此函數設定視圖控制器載入後最先顯示的方向,UIInterfaceOrientation是一個結構體,支援的取值如下
UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
- (NSUInteger)supportedInterfaceOrientations
此函數設定視圖控制器支援的方向(需要shouldAutorotate返回YES),支援的取值如下
UIInterfaceOrientationMaskPortrait
UIInterfaceOrientationMaskLandscapeLeft
UIInterfaceOrientationMaskLandscapeRight
UIInterfaceOrientationMaskPortraitUpsideDown
UIInterfaceOrientationMaskLandscape
UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown)
UIInterfaceOrientationMaskAllButUpsideDown
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
使用者介面即將旋轉時觸發此函數,toInterfaceOrientation表示即將到達的方向
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
使用者介面旋轉結束時觸發此函數,fromInterfaceOrientation表示旋轉前的方向
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
使用者介面旋轉過程中觸發此函數,一般在此函數中定製翻轉後控制項的位置和大小
所以在上面那個執行個體中我們先將6個UIVIew控制項連結到視圖控制器中,然後在willAnimateRotationToInterfaceOrientation:duration:中修改旋轉後的介面
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { self.view1.frame = CGRectMake(50, 20, 110, 130); self.view2.frame = CGRectMake(225, 20, 110, 130); self.view3.frame = CGRectMake(400, 20, 110, 130); self.view4.frame = CGRectMake(50, 180, 110, 130); self.view5.frame = CGRectMake(225, 180, 110, 130); self.view6.frame = CGRectMake(400, 180, 110, 130); }}
上面代碼在旋轉到橫屏時修改view控制項的位置,因為我們strobyboard中預設布局了豎直狀態下的介面,所以在代碼中不需要重新布局view控制項豎直狀態時的位置,但是如果我們是用編碼方式放置的控制項,那麼需要在上面代碼中添加一個else,設定豎屏後的介面。
IOS重力感應