如何在Swift中将我的标签返回到它的初始位置(UIGestureRecognizer)

时间:2015-05-12 16:08:02

标签: swift uigesturerecognizer

我正在屏幕上移动一个标签,我想让它从我的手指上移开后再回到它的初始位置,现在它就停留在那里!任何帮助将不胜感激。

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) { 
    let translation = recognizer.translationInView(self.view)

    if let view = recognizer.view {
        view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y)
    }
    recognizer.setTranslation(CGPointZero, inView: self.view)

    if recognizer.state == UIGestureRecognizerState.Ended {
        //What code to add to return my Label to it's initial position??
    }
}

2 个答案:

答案 0 :(得分:3)

在开始拖动时将初始中心位置view.center保存在变量中,当您最终移动UIView时,再次设置此值。

试试这个:

import UIKit

class ViewController: UIViewController {

var initial : CGPoint?

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
    if let view = recognizer.view {
        if recognizer.state == UIGestureRecognizerState.Began {
           initial = view.center
        }
        else if recognizer.state == UIGestureRecognizerState.Ended {
           view.center = initial!
           return
        }

        let translation = recognizer.translationInView(self.view)
        view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y)
        recognizer.setTranslation(CGPointZero, inView: self.view)
    }
  }
}

答案 1 :(得分:0)

我相信在函数touchesEnded内你可以重置标签的位置。

希望有所帮助:)