IOS重力传感器

电脑杂谈  发布时间:2020-04-26 16:12:27  来源:网络整理

ios重力感应失效解决_苹果7重力感应失效解决_ios重力感应失效解决

iPhone和iPad设备有四个方向,我们可以根据应用程序的当前方向调整界面.

为了使应用程序支持不同的方向,首先我们需要在项目设置中设置设备支持的方向(也可以在项目的plist中设置)

将肖像与屏幕底部的主页按钮垂直放置

上下颠倒垂直放置,并且主页按钮位于屏幕顶部

风景水平向左,主页按钮位于屏幕左侧

横向在水平方向上,主页按钮位于屏幕右侧

我们在StoryBoard中拖动了一个新的ViewController,绑定了其文件的所有者,并放置了6个UIView,设置了不同的背景颜色

ios重力感应失效解决_ios重力感应失效解决_苹果7重力感应失效解决

程序运行后,我们旋转模拟器,发现在垂直和水平屏幕上,界面显示如下

显然,此显示不适用于横向模式. 为了获得合适的显示效果,我们需要在ViewController中编写一些代码.

首先让我们看一下与ViewController中重力感应相关的一些功能

-(BOOL)应该自动旋转

此函数返回YES表示视图控制器支持重力感应,返回NO表示视图控制器不支持重力感应

苹果7重力感应失效解决_ios重力感应失效解决_ios重力感应失效解决

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation

此功能设置在加载视图控制器后首先显示的方向. UIInterfaceOrientation是一个结构ios重力感应失效解决,支持的值如下

UIInterfaceOrientationPortrait

UIInterfaceOrientationPortraitUpsideDown

UIInterfaceOrientationLandscapeLeft

UIInterfaceOrientationLandscapeRight

-(NSUInteger)支持的InterfaceOrientations

此函数设置视图控制器支持的方向(需要shouldAutorotate返回YES),支持的值如下

ios重力感应失效解决_ios重力感应失效解决_苹果7重力感应失效解决

UIInterfaceOrientationMaskPortrait

UIInterfaceOrientationMaskLandscapeLeft

UIInterfaceOrientationMaskLandscapeRight

UIInterfaceOrientationMaskPortraitUpsideDown

UIInterfaceOrientationMaskLandscape

UIInterfaceOrientationMaskAll =(UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown)

UIInterfaceOrientationMaskAllButUpsideDown

-(void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)到InterfaceOrientation持续时间: (NSTimeInterval)持续时间

ios重力感应失效解决_ios重力感应失效解决_苹果7重力感应失效解决

该功能将在用户界面即将旋转时触发,并且toInterfaceOrientation指示要达到的方向

-(void)didRotateFromInterfaceOrientation: (UIInterfaceOrientation)fromInterfaceOrientation

此功能在用户界面旋转结束时触发,fromInterfaceOrientation指示旋转之前的方向

-(void)willAnimateRotationToInterfaceOrientation: (UIInterfaceOrientation)到InterfaceOrientation持续时间: (NSTimeInterval)持续时间

在旋转用户界面期间触发此功能. 通常,翻转后控件的位置和大小是在此功能中自定义的

因此在上面的示例中,我们首先将六个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);
    }
}

上面的代码将视图控件旋转到水平屏幕时将其位置更改. 因为默认情况下,我们的strobyboard将界面布置为垂直状态ios重力感应失效解决,所以无需在代码中重新布置垂直状态下视图控件的位置. 我们将控件置于编码模式,因此我们需要在上面的代码中添加else,以在垂直屏幕之后设置界面.


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/sanxing/article-189715-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...