2011-07-01 74 views
1

我使用UIView的+ animateWithDuration:delay:options:animations:completion:方法在幾秒鐘左右的時間內沿着一條線移動我的視圖。UIView動畫確定中心動畫

我想確定,在這個動畫的任意時間,UIView與它正在移動的路徑一起。但是,當我這樣做並嘗試訪問centerframe時,我發現該位置已被設置爲最終目的地。

我這樣做的原因是我有一個NSTimer每隔0.1秒觸發一次,它會更新父視圖以顯示UIView以前的行。我希望能夠隨着UIView的移動而保持更新。

有關如何做到這一點的任何想法?我發現的唯一類似問題是http://forums.macrumors.com/showthread.php?t=1056105,但沒有顯示分辨率。

另外...有沒有更好的方法來做到這一點?

謝謝!

回答

10

UIViews由CALayers支持,它是實際動畫的圖層。 CALayer公開了一個屬性presentationLayer,該屬性在訪問時返回CALayer的副本,該副本儘可能地表示用戶可見的當前狀態。通過詢問view.layer.presentationLayer.frame,您可以立即獲取圖層的框架,以便用戶可以看到,並且這對應於UIView的框架。

+0

Perfect-非常感謝! –

0

我知道它太晚了,但也許它可以幫助別人。

CALayer具有呈現()函數

FUNC呈現() 返回表示層的狀態,因爲它當前屏幕上顯示的表示層對象的副本。

表示層有一個框架屬性什麼是CGRect並從這裏容易計算出中點。

演示

enter image description here

的代碼在迅速3

class ViewController: UIViewController { 
     var circle : UIView! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     let animator = UIViewPropertyAnimator(duration: 10, curve: .easeInOut) 
     circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0)) 
     circle.layer.cornerRadius = 20.0 
     circle.backgroundColor = UIColor.blue 
     self.view.addSubview(circle) 
     Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) 
     { 
      [weak self] (myTimer) -> Void in 
      if let movingBlueDotFrame = self?.circle.layer.presentation()?.frame 
      { 
       let blueDotOriginPoint = movingBlueDotFrame.origin 
       let blueDotMiddlePoint = CGPoint(x: blueDotOriginPoint.x + movingBlueDotFrame.width/2, y: blueDotOriginPoint.y + movingBlueDotFrame.height/2) 
       print(blueDotMiddlePoint) 
       if blueDotMiddlePoint == CGPoint(x:100,y:100){ 
        print("Yeeaahh") 
        myTimer.invalidate() 
       } 
      } 
     } 
     animator.addAnimations { 
      self.circle.center = CGPoint(x: 100,y: 100) 
     } 
     animator.startAnimation() 
    } 
}