Switch或If语句中的Swift变量

时间:2018-11-08 16:21:38

标签: ios swift variables

我正在尝试学习如何使用Swift,而我才刚刚开始。因此,这段代码可能非常糟糕。我在var语句中找不到有关switch处理的信息。

在iOS应用中,您可以沿屏幕拖动黑色视图(imgView)。现在,如果触摸结束,则imgView应该设置为CGPoint的动画,该CGPoint是根据平移手势的起点和终点计算的。

@objc func handlePan(recognizer: UIPanGestureRecognizer) {

    var locationOfBeganTap  = CGPoint()
    var locationOfEndTap = CGPoint()
    let finalDestination = CGPoint(x: (locationOfBeganTap.x  + locationOfEndTap.x), y: locationOfBeganTap.y  + locationOfEndTap.y)


    switch recognizer.state {

    case .changed, .began:

        locationOfBeganTap = recognizer.location(in: screenView)
        print(locationOfBeganTap)

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

    case .ended:

        locationOfEndTap = recognizer.location(in: screenView)

        UIView.animate(withDuration: 2.0, animations: {
            print(locationOfBeganTap)

            self.imgView.center = finalDestination
        })

    default:
        break
    }

我想知道为什么在.began上正确设置了变量“ locationOfBeginTap”,但是在Switch语句中,进一步将变量再次设置为0。它何时以及为何发生变化?而我该如何避免呢?

2 个答案:

答案 0 :(得分:1)

这都是关于可变范围的。这与switchif无关。每次调用handlePan时,您都会用其初始值创建新的局部变量。

将这些变量的声明移到函数之外,因此它们实际上是类的属性。然后,这些值将保留在对handlePan的调用之间。

答案 1 :(得分:0)

将变量移到方法之外。

var locationOfBeganTap  = CGPoint()
var locationOfEndTap = CGPoint()
let finalDestination = CGPoint(x: (locationOfBeganTap.x  + locationOfEndTap.x), y: locationOfBeganTap.y  + locationOfEndTap.y)

@objc func handlePan(recognizer: UIPanGestureRecognizer) {

    switch recognizer.state {

    case .changed, .began:

        locationOfBeganTap = recognizer.location(in: screenView)
        print(locationOfBeganTap)

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

    case .ended:

        locationOfEndTap = recognizer.location(in: screenView)

        UIView.animate(withDuration: 2.0, animations: {
            print(locationOfBeganTap)

            self.imgView.center = finalDestination
        })

    default:
        break
    }
}