2015-03-08 92 views
0

我在swift中使用加速度计的代码,但是当条件为真时,我需要为视图设置动画效果,但不是动画效果。在Swift中使用加速度计

我该怎么做动画。由于

import CoreMotion 

lazy var motionManager = CMMotionManager() 


override func viewDidAppear(animated: Bool) { 
    super.viewDidLoad() 

    if motionManager.accelerometerAvailable{ 
     let queue = NSOperationQueue() 
     motionManager.startAccelerometerUpdatesToQueue(queue, withHandler: 
      {(data: CMAccelerometerData!, error: NSError!) in 

       if data.acceleration.x <= -0.22 && data.acceleration.x >= -0.24 { 

         UIView.animateWithDuration(1 ,delay: 0, options: .CurveEaseInOut | .AllowUserInteraction, 
          animations: { 

           self.text.frame = CGRectMake(100, 0, 42,21) 
         }, 
         completion:{ finished in 

        }) 

       } 

      } 
     ) 
    } else { 
     println("Accelerometer is not available") 
    } 

} 
+1

目前还不清楚你问什么,但'viewDidLoad'肯定不会做任何动画正确的位置。在这一点上,该视图甚至不在屏幕上。 – Paulw11 2015-03-08 21:17:24

+0

我试过了。在viewDidAppear和不起作用。我能做什么?谢谢。 – Fabio 2015-03-08 22:24:54

+0

我没有注意到你正在注册一个回调处理程序。您应该在主队列上调用动画,因为您可能会从后台线程调用该动画。另外,设置一个断点来确认你的处理程序正在被调用,并且测试在处理程序之外运行你的动画,以确认代码不需要你想要的东西 – Paulw11 2015-03-08 22:31:53

回答

0
import CoreMotion 

lazy var manager = CMMotionManager() 


if manager.accelerometerAvailable { 
     manager.accelerometerUpdateInterval = 0.2 
     manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { 
      [weak self] (data: CMAccelerometerData!, error: NSError!) in 

      if data.acceleration.x >= 0.1 { 

       var petalo1 = UIImageView() 

       petalo1.image = UIImage(named: "petalo1.png") 
       petalo1.frame = CGRectMake (20, 75, 75, 75) 
       self?.view.addSubview(petalo1) 


       UIView.animateWithDuration(4 ,delay: 0, options: .CurveEaseInOut | .AllowUserInteraction, 
        animations: { 
         petalo1.frame = CGRectMake (20, 811, 75, 75) 
        }, 
        completion:{ finished in 
         petalo1.removeFromSuperview() 
       }) 

      } 
     } 
    }else { 
       println("Accelerometer is not available") 
    } 
0

斯威夫特3语法

lazy var motionManager = CMMotionManager() 
if motionManager.isAccelerometerAvailable { 

     motionManager.accelerometerUpdateInterval = 0.2 

     motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in 
      if let myData = data 
      { 
       if myData.acceleration.x >= 0.1 { 

        let petalo1 = UIImageView() 

        petalo1.image = UIImage(named: "petalo1.png") 
        petalo1.frame = CGRect(x: 20, y: 75, width: 75, height: 75) 
        self.view.addSubview(petalo1) 


        UIView.animate(withDuration: 4 ,delay: 0, options: [.curveEaseOut, .allowUserInteraction], animations: { 
         petalo1.frame = CGRect(x: 20, y: 811, width: 75, height: 75) 
        }, completion:{ finished in 
         petalo1.removeFromSuperview() 
        }) 
       } 
      } 
     } 
    }