简体   繁体   English

对象停止移动-UIDynamics和Swift iOS

[英]Objects stop moving - UIDynamics and Swift iOS

I am trying to add gravity to a group of buttons so they move around the screen when the device is tilted. 我试图将重力添加到一组按钮上,以使设备倾斜时它们在屏幕上移动。 The objects move and so long as the device is always in motion they keep moving, but once the device is still for at least 1 second, they stop moving completely, and stick to the edge even if I move the device after that. 物体会移动,只要设备始终处于运动状态,它们就会一直移动,但是一旦设备静止至少1秒钟,它们就会完全停止移动,并且即使在此之后我移动设备也要坚持到边缘。

Here is my code: 这是我的代码:

In the ViewController.Swift 在ViewController.Swift中

var animator: UIDynamicAnimator!
var gravity: UIGravityBehavior!
var collision: UICollisionBehavior!


var motionManager = CMMotionManager()
var motionQueue = NSOperationQueue()
let itemBehavior = UIDynamicItemBehavior()

These two are called int he ViewDidLoad() 这两个称为int in ViewDidLoad()

 func addBehaviours (){

    animator = UIDynamicAnimator(referenceView: view)
    gravity = UIGravityBehavior(items: [emailButton,facebookButton])
    animator.addBehavior(gravity)
    itemBehavior.friction = 0.1;
    itemBehavior.elasticity = 0.5
    animator?.addBehavior(itemBehavior)

    collision = UICollisionBehavior(items: [emailButton, facebookButton])
    collision.translatesReferenceBoundsIntoBoundary = true
    animator.addBehavior(collision)
    itemBehavior.addItem(emailButton)
    itemBehavior.addItem(facebookButton)
}

func updateMotion () {

    motionManager.startDeviceMotionUpdatesToQueue(motionQueue) { (motion: CMDeviceMotion?, error: NSError?) -> Void in


        self.gravity.gravityDirection = CGVectorMake(CGFloat((motion?.gravity.x)!), -CGFloat((motion?.gravity.y)!))


    }

}

First, reduce the rate of updates by setting the motion manager's deviceMotionUpdateInterval to something like 0.2 (ie, much less often than the animator's frame rate). 首先,通过将运动管理器的deviceMotionUpdateInterval设置为deviceMotionUpdateInterval 0.2 (即,比动画师的帧频少deviceMotionUpdateInterval来降低更新率。 Then, change this line: 然后,更改此行:

motionManager.startDeviceMotionUpdatesToQueue(motionQueue) { // ...

to this: 对此:

motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) { // ...

Everything you are planning to do in your handler involves talking to the animator or its allies (ie the gravity behavior), and that needs to be done on the main thread. 您计划在处理程序中执行的所有操作都涉及与动画师或其盟友进行对话(即重力行为),而这需要在主线程上完成。 So there is no point receiving your updates on a background queue, as you are doing now, because you need to get onto the main thread immediately anyway. 因此,没有必要像现在那样在后台队列上接收更新,因为无论如何您都需要立即进入主线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM