我正在努力学习如何使用 Swift,而我才刚刚开始。所以这段代码可能非常糟糕。我在 switch
语句中找不到有关 var
处理的一些信息。
在 iOS 应用程序中,您可以沿屏幕拖动黑色 View (imgView)。现在,如果触摸结束,imgView 应该动画到一个 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。何时以及为何发生变化?我怎样才能避免这种情况?
最佳答案
一切都与变量范围有关。这与 switch
或 if
无关。每次调用 handlePan
时,您都会创建具有初始值的新局部变量。
将这些变量的声明移到函数之外,这样它们实际上就是您的类的属性。然后这些值将在调用 handlePan
之间保留。
关于ios - Switch 或 If 语句中的 Swift 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53211910/