中断animateWithDuration
问题描述:
我有一个动画计时器条向下计数,我希望能够取消动画并在满足特定条件时重置条,因此它不会一直变为0.同样,如果它确实为0,我想调用一个函数。中断animateWithDuration
现在我只需要一个按钮来测试。再次按下按钮可以防止它一直向下,但是它会在屏幕上弹出,并且完成块中的打印语句总是返回。我认为多个动画正在堆叠在一起。
如何停止动画?
var countDownBar = UIView()
var button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Place the countDownBar in the center of the view
countDownBar.frame = CGRectMake(0, 0, 150, 15)
countDownBar.center = view.center
countDownBar.backgroundColor = UIColor.blueColor()
view.addSubview(countDownBar)
// Add in a button
button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(0, 0, 50, 20)
button.center = CGPointMake(view.center.x, view.center.y + 30)
button.backgroundColor = UIColor.lightGrayColor()
button.setTitle("button", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
}
// Do this when the button is pressed
func buttonAction (sender: UIButton) {
// Shrink the bar down to 0 width
UIView.animateWithDuration(3.0,
animations: ({
self.countDownBar.frame = CGRectMake(self.countDownBar.frame.minX, self.countDownBar.frame.minY, 0, self.countDownBar.frame.height)
}),
completion: {finished in
// When finished, reset the bar to its original length
self.countDownBar.frame = CGRectMake(0, 0, 150, 15)
self.countDownBar.center = self.view.center
// Display if completed fully or interrupted
if finished {
print("animation finished")
} else {
print("animation interrupted")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
答
新usingSpringWithDamping动画调用设置选项AllowUserInteration能做到这一点,如果我正确理解你的问题。
animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
此外,大厦可中断,并从这里的WWDC 2014的谈话响应交互会话:https://developer.apple.com/videos/wwdc/2014/可能是一个有用的资源(他们解释这是如何工作的更详细)。