【问题标题】:Parallax effect with UIMotionEffect not workingUIMotionEffect 的视差效果不起作用
【发布时间】:2020-05-21 04:18:57
【问题描述】:

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。

【问题讨论】:

  • imageView 是您将效果应用于表格或集合视图的一部分吗?如果是这样,您可能需要查看:stackoverflow.com/questions/19319722/…
  • 不,它只是普通的 UIImageView,受限于 superview

标签: ios swift uikit parallax uimotioneffect


【解决方案1】:

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

这些枚举的 Apple 文档是 here

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

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

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

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

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

【讨论】:

  • 非常感谢!!!!!!它的工作原理仔细检查设置>辅助功能>运动>减少运动没有打开。因为如果开启了,那么 UIInterpolatingMotionEffect 就不起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多