ios - UIMotionEffect 的视差效果不起作用

标签 ios swift uikit parallax uimotioneffect

我对 UIView 的视差效果根本不工作。我需要像 iPhone 倾斜(伪 3D)上的移动背景图像。

let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
horizontalMotionEffect.minimumRelativeValue = -50
horizontalMotionEffect.maximumRelativeValue = 50

let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = -50
verticalMotionEffect.maximumRelativeValue = 50

let motionEffectGroup = UIMotionEffectGroup()
motionEffectGroup.motionEffects = [horizontalMotionEffect, verticalMotionEffect]

imageView.addMotionEffect(motionEffectGroup)

我试过使用这段代码。我已阅读 https://www.hackingwithswift.com/example-code/uikit/how-to-create-a-parallax-effect-in-uikit但我的imageView保持静止。

我正在使用 Xcode 11、iOS 13。

最佳答案

在您共享的代码中,我注意到的一件事是您使用了大写 T在枚举中 .TiltAlongHorizontalAxis.TiltAlongVerticalAxis ,不编译(至少在 Xcode 11.4.1 上)-> 需要更改为小写 T .

这些枚举的 Apple 文档是 here .

除此之外,我认为您共享的代码没有任何问题。事实上,我用一个简单的 imageView 创建了一个示例项目。在我添加约束的 View 中,它会填满其父 View 的整个空间。

然后,我添加了您共享的运动效果代码,并在实际设备 (iPad Pro) 上运行它。它工作得很好。

您能否检查一些可能是问题根源的事情:

  • 仔细检查 Settings > Accessibility > Motion > Reduce Motion未开启。因为如果开启的话,那么UIInterpolatingMotionEffect不会工作。
  • 测试您正在测试的设备的加速度计是否实际工作。或者更好的是,使用其他设备进行测试。 (这在模拟器上不起作用)。
  • 如果您正在编辑 imageView 的框架在任何地方的代码中(或特别是在 viewWillLayout/viewDidLayout 中),你不应该这样做。

  • 无论如何,如果这些都不能帮助您解决问题,您能否创建一个简单的示例项目来演示该错误并将其发布到 Github 上?如果我真的可以重现问题,我可以尝试提供帮助。

    关于ios - UIMotionEffect 的视差效果不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61927204/

    相关文章:

    ios - 放置在 UINavigationItem 中时 UISearchController 出现故障 - iOS 11+

    iphone - UIView 背景颜色影响 iOS 5 中的触摸

    iphone - "Incompatible pointer to integer conversion"使用方 block 时

    ios - UITableView 是否可以按页滚动?

    ios - SpriteKit - CPU/Memory leak on segue back to main screen

    iOS 相机应用程序 swift 3

    objective-c - UIActionSheet 总是在 View 的顶部

    swift - 在 sprite kit 中创建高效的平铺背景

    ios - fatal error : unexpectedly found nil while unwrapping an Optional value Parse sign up

    swift - 为 presentedViewController 设置委托(delegate)(例如不使用 segues)