我有一个简单的手势识别器。当手势为“向上”时,菜单向上滑动。 “DOWN”:菜单向下滑动。这有效。
我也有一个计时器。它只是每秒计算一个数字++。这也有效。但计时器一起导致我的 GUI 崩溃。 动画正确启动,但是当计时器调用我的计数器方法时,它会跳回原始 GUI。
这是什么问题?我在谷歌上什么也没找到,但我想我搜索了错误的词。 (英语不是我的母语,德语也没有那么多文献......)
这是我的代码片段:
class ViewController: UIViewController, MKMapViewDelegate{
@IBOutlet weak var swipe: UILabel!
var number: Int = 0
@IBOutlet weak var menuView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
var topSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
var downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
topSwipe.direction = .Up
downSwipe.direction = .Down
view.addGestureRecognizer(topSwipe)
view.addGestureRecognizer(downSwipe)
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "counter", userInfo: nil, repeats: true)
}
func counter() {
number++
swipe.text = "\(number)"
}
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .Up) {
print("TOP")
var menuPosition = CGPointMake(self.menuView.frame.origin.x, self.menuView.frame.origin.y - 100.0)
UIView.animateWithDuration(0.65, animations: {
self.menuView.frame = CGRectMake(menuPosition.x,menuPosition.y,self.menuView.frame.size.width,self.menuView.frame.size.height)
})
}
if (sender.direction == .Down) {
menuChoose = true
UIView.animateWithDuration(0.65, animations: {
var menuPosition = CGPointMake(self.menuView.frame.origin.x, self.menuView.frame.origin.y + 100.0)
self.menuView.frame = CGRectMake(menuPosition.x,menuPosition.y,self.menuView.frame.size.width,self.menuView.frame.size.height)
})
}
}
}
我试图锁定计时器。因此,当手势开始时,只需计算数字即可,无需 swipe.text = "(number)" 动画结束,但“解锁”后 GUI 跳回原点。
感谢您提供一些我可以搜索的代码片段或关键字:)
最佳答案
似乎每当设置 UILabel
的 text
属性时,它都会重新绘制 View ,从而导致重置 menuView
的位置(也许有人可以在评论中详细说明“为什么”)。如果您使用自动布局约束来操纵 menuView
的位置,它就可以工作。您可以通过设置 spaceConstraint.constant += 100
或 spaceConstraint.constant -= 100
然后调用
UIView.animateWithDuration(0.65, animations: {
self.view.layoutIfNeeded()
})
关于swift:计时器(每秒)+gestureRecognizer 使 GUI 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33219384/