首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何调整CMMotionManager数据以适应iOS 8下的方向?

如何调整CMMotionManager数据以适应iOS 8下的方向?
EN

Stack Overflow用户
提问于 2014-09-05 18:16:29
回答 2查看 472关注 0票数 0

我的应用程序使用CMMotionManager来跟踪设备运动,但是iOS总是以标准的设备方向(底部的home按钮)返回设备运动数据。

为了使运动数据与我的UIView相同的方向,我将视图从视图向下积累到窗口,如下所示:

代码语言:javascript
复制
CGAffineTransform transform = self.view.transform;
for (UIView *superview = self.view.superview; superview; superview = superview.superview) {
    CGAffineTransform superviewTransform = superview.transform;
    transform = CGAffineTransformConcat(transform, superviewTransform);
}

这种转换在iOS 6& 7下得到了正确的计算,但是iOS 8改变了旋转模型,现在视图总是返回身份转换(没有旋转),不管设备是如何定向的。但是,来自运动管理器的数据仍然固定在标准的方向上。

监视UIDevice旋转通知和手动计算四个转换似乎是在iOS 8下实现此转换的一种方法,但它似乎也很糟糕,因为设备方向不一定与我的视图方向相匹配(也就是说,iPhone上的优点是通常不支持的设备方向)。

将CMMotionManager的输出转换为iOS 8下特定UIView的方向的最佳方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-06 01:23:03

我找不到直接计算转换的方法,因此我更改了代码,以便在视图控制器中接收到willRotateToInterfaceOrientation: message时手动计算设置转换,如下所示:

代码语言:javascript
复制
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    CGAffineTransform transform;
    switch (toInterfaceOrientation) {
        case UIInterfaceOrientationLandscapeLeft:
            transform = CGAffineTransformMake(
                0, -1,
                1, 0,
                0, 0);
            break;

        case UIInterfaceOrientationLandscapeRight:
            transform = CGAffineTransformMake(
                0, 1,
                -1, 0,
                0, 0);
            break;

        case UIInterfaceOrientationPortraitUpsideDown:
            transform = CGAffineTransformMake(
                -1, 0,
                0, -1,
                0, 0);
            break;

        case UIInterfaceOrientationPortrait:
            transform = CGAffineTransformIdentity;
            break;
    }
    self.motionTransform = transform;
}
票数 0
EN

Stack Overflow用户

发布于 2016-07-21 18:52:30

虽然不是很明显,但在iOS 8和更高版本中,推荐的方法是使用转换协调器。

viewWillTransition(to:with:)中,协调器可以在其调用的任何方法的完成块中传递一个采用UIViewControllerTransitionCoordinatorContext的对象( UIKit使用的默认协调器实际上是它自己的上下文,但不一定是这样)。

上下文的targetTransform属性是在动画结束时应用于接口的旋转。注意,这是一个相对的转换,而不是接口的绝对转换。

代码语言:javascript
复制
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    let animation: (UIViewControllerTransitionCoordinatorContext) -> Void = { context in
        // Update animatable properties.
    }

    coordinator.animate(alongsideTransition: animation) { context in
        // Store or use the transform.
        self.mostRecentTransform = context.targetTransform
    }
}

虽然旧的方法仍然有效,但是当您需要协调动画转换时,例如在使用图形框架或使用自定义布局时,这个API会更灵活一些。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25691721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档