我正在使用以下代码体验运动效果振荡 import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions lau
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.rootViewController = ExampleController() self.window!.makeKeyAndVisible() return true } } class ExampleController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let redView = UIView(frame: CGRect(x: 200, y: 200, width: 800, height: 500)) redView.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5) self.view.addSubview(redView) let effect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis) effect.minimumRelativeValue = -100 effect.maximumRelativeValue = 100 let effectGroup = UIMotionEffectGroup() effectGroup.motionEffects = [effect] redView.motionEffects = [effectGroup] } }
在Simulator和新Apple TV上导致以下行为
有没有办法避免振荡?
我在模拟器中尝试了你的代码,打印水平偏移:public class MyMotionEffect : UIInterpolatingMotionEffect { public override func keyPathsAndRelativeValuesForViewerOffset(viewerOffset: UIOffset) -> [String : AnyObject]? { print("\(viewerOffset.horizontal)") return super.keyPathsAndRelativeValuesForViewerOffset(viewerOffset); } }
过了一会儿,我可以重现振荡.生成的(水平)偏移量具有以下图表:
您可以看到倾斜中已经存在振荡.设备似乎一次产生两个倾斜.
一种解决方案是添加启发式方法(将偏移值与前两个进行比较并忽略是否存在符号更改,或忽略具有突然更改的偏移.不幸的是,这两种解决方案都不完美).最好的解决方案可能是直接使用Core Motion并完全避免本机转换.或者使用较小的距离,因为振动将不可见.