2015-03-08 98 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() 
        }) 
       } 
      } 
     } 
    }