UIPanGestureRecognizer拖动图像视图 - 如果我再次拖动,比例会爆炸

时间:2015-04-10 22:40:16

标签: ios objective-c swift uigesturerecognizer

我正在努力让图像视图在拖动时变小,然后在用户停止拖动时重置。它第一次完美运行,但在第二次拖动时,UIImage的帧超过100%(在这种情况下超过200x200)。请指教。我已经尝试了很多东西,你可以看到,我一直在打印到控制台看看发生了什么,但我不知道为什么帧会在第二次变大。谢谢!

var xFromCenter: CGFloat = 0
var mainPic = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.mainPic.frame = CGRectMake(self.view.bounds.width / 2 - 100, self.view.bounds.height / 2, 200, 200)
    self.mainPic.backgroundColor = UIColor.blueColor()
    self.view.addSubview(self.mainPic)

    var gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
    mainPic.addGestureRecognizer(gesture)
    mainPic.userInteractionEnabled = true

}

func wasDragged(gesture: UIPanGestureRecognizer) {

    let translation = gesture.translationInView(self.view)
    var mainPic = gesture.view!

    xFromCenter += translation.x

    var scale = min(80 / abs(xFromCenter), 1)

    mainPic.center = CGPoint(x: mainPic.center.x + translation.x, y: mainPic.center.y)

    gesture.setTranslation(CGPointZero, inView: self.view)

    mainPic.transform = CGAffineTransformScale(self.view.transform, scale, scale)

    println(xFromCenter)
    println(scale)
    println(self.mainPic.frame)

    if gesture.state == UIGestureRecognizerState.Ended {

        self.mainPic.frame = CGRectMake(self.view.bounds.width / 2 - 100, self.view.bounds.height / 2, 200, 200)

        xFromCenter = 0

        println(xFromCenter)
        println(scale)

    }
}

1 个答案:

答案 0 :(得分:1)

您需要在重置尺寸之前重置比例。

像这样:

if gesture.state == UIGestureRecognizerState.Ended {
    // Add this line:
    self.mainPic.transform = CGAffineTransformIdentity
    self.mainPic.frame = CGRectMake(self.view.bounds.width / 2 - 100, self.view.bounds.height / 2, 200, 200)
...

我对此进行了测试(在xcode 6.3中)并且有效。