IOS重力感应
iPhone和iPad設(shè)備有4個(gè)方向的狀態(tài),我們可以針對(duì)應(yīng)用當(dāng)前所處的方向調(diào)整界面。
為了使應(yīng)用支持不同的方向,首先我們需要在項(xiàng)目設(shè)置中設(shè)置設(shè)備支持的方向(也可以在項(xiàng)目的plist中設(shè)置)
Portrait 豎放,home鍵在屏幕下方
Upside Down 豎放,home鍵在屏幕上方
Landscape Left 橫放,home鍵在屏幕左方
Landscape Right 橫放,home鍵在屏幕右方
?
我們在StoryBoard中拖入一個(gè)新的ViewController,綁定好它的File's Owner,然后放入6個(gè)UIView,設(shè)置好不同的背景色
?
程序運(yùn)行后,我們在旋轉(zhuǎn)模擬器,發(fā)現(xiàn)在豎屏和橫屏狀態(tài)下,界面顯示如下
?
?
顯然橫屏狀態(tài)下這樣的顯示是不適合的,為了得到合適的顯示效果,我們需要在ViewController中寫一些代碼。
首先我們先看一下在ViewController中和重力感應(yīng)相關(guān)的一些函數(shù)
- (BOOL)shouldAutorotate
此函數(shù)返回YES表示此視圖控制器支持重力感應(yīng),返回NO表示此視圖控制器不支持重力感應(yīng)
?
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
此函數(shù)設(shè)置視圖控制器加載后最先顯示的方向,UIInterfaceOrientation是一個(gè)結(jié)構(gòu)體,支持的取值如下
UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
?
- (NSUInteger)supportedInterfaceOrientations
此函數(shù)設(shè)置視圖控制器支持的方向(需要shouldAutorotate返回YES),支持的取值如下
UIInterfaceOrientationMaskPortrait
UIInterfaceOrientationMaskLandscapeLeft
UIInterfaceOrientationMaskLandscapeRight
UIInterfaceOrientationMaskPortraitUpsideDown
UIInterfaceOrientationMaskLandscape
UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown)
UIInterfaceOrientationMaskAllButUpsideDown?
?
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration?
用戶界面即將旋轉(zhuǎn)時(shí)觸發(fā)此函數(shù),toInterfaceOrientation表示即將到達(dá)的方向
?
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
用戶界面旋轉(zhuǎn)結(jié)束時(shí)觸發(fā)此函數(shù),fromInterfaceOrientation表示旋轉(zhuǎn)前的方向
?
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
用戶界面旋轉(zhuǎn)過程中觸發(fā)此函數(shù),一般在此函數(shù)中定制翻轉(zhuǎn)后控件的位置和大小
?
所以在上面那個(gè)實(shí)例中我們先將6個(gè)UIVIew控件連結(jié)到視圖控制器中,然后在willAnimateRotationToInterfaceOrientation:duration:中修改旋轉(zhuǎn)后的界面
?
- (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);} }?
上面代碼在旋轉(zhuǎn)到橫屏?xí)r修改view控件的位置,因?yàn)槲覀僺trobyboard中默認(rèn)布局了豎直狀態(tài)下的界面,所以在代碼中不需要重新布局view控件豎直狀態(tài)時(shí)的位置,但是如果我們是用編碼方式放置的控件,那么需要在上面代碼中添加一個(gè)else,設(shè)置豎屏后的界面。
轉(zhuǎn)載于:https://www.cnblogs.com/zanglitao/p/4051706.html
總結(jié)
- 上一篇: mac SecureCRT设置
- 下一篇: 依赖注入之针对不同类型变量的几种注入方式