我正在使用滑动手势识别器通过向上滑动和向下滑动来增加和减少我的计数器。
当我向上滑动时,我也会将我的标签偏移 +10,当我向下滑动时,我也会将我的标签偏移 -10。
一切都很好,但是一旦我向上滑动,我的标签偏移量就会回到 0。 我的目标是在向上滑动时将偏移量保持在 +10。 这是我的代码:
private func setupSwipeGestures() {
var swipeUp = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
var swipeDown = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
swipeUp.direction = .Up
swipeDown.direction = .Down
view.addGestureRecognizer(swipeUp)
view.addGestureRecognizer(swipeDown)
}
func handleSwipes(sender:UISwipeGestureRecognizer) {
let increment: Int
let offset: CGFloat
// up or down
if sender.direction == .Up {
increment = 1
offset = 10
} else {
increment = -1
offset = -10
}
问题:
- 是否有解决方案可以让标签在向上滑动时保持 +10 的偏移量,而在向下滑动时保持 -10 的偏移量?
最佳答案
我从你的问题中了解到,你想在向上滑动时存储 +10 值,你可以通过购买声明你的 increment
和 offset
全局到类中来做到这一点如下所示:
class ViewController: UIViewController {
//Declare it below your class declaration
var increment = 0
var offset: CGFloat = 0
}
在您的代码中,您将这两个变量声明到您的 handleSwipes
函数中,这样当您调用此函数时,它将变为 0,并且您的偏移量将始终变为 +10 或 -10,但是一旦您声明它全局进入类,一旦获得它就会保留它的值,如果你想在每次 handleSwipes
函数调用时增加它,那么你可以这样做:
offset += 10
offset -= 10
同样的事情也会发生在您的 increment
变量上,您可以根据需要更改它,之后您可以通过这种方式将标签位置更改到您的 handleSwipes
函数中:
yourLbl.center = CGPoint(x: yourLbl.center.x, y: yourLbl.center.y + offset)
你的handleSwipes
函数将是:
func handleSwipes(sender:UISwipeGestureRecognizer) {
// up or down
if sender.direction == .Up {
increment = 1
offset += 10
println(offset)
yourLbl.center = CGPoint(x: yourLbl.center.x, y: yourLbl.center.y + offset)
} else {
increment = -1
offset -= 10
println(offset)
yourLbl.center = CGPoint(x: yourLbl.center.x, y: yourLbl.center.y + offset)
}
}
希望这会有所帮助。
关于ios - 如何使用 Swipe 手势识别器进行长按?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771217/