我对 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/