アニメーションを停止し、アニメーションの完了関数が呼び出されて TRUE 変数が返されないようにするのが困難です。
次のコードは、同じ問題が存在する私のコードの簡略版です。
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
viewButtonStart.frame = CGRect(x: 10, y: 10, width: 100, height: 100)
viewButtonStart.backgroundColor = UIColor.greenColor()
let gesture = UITapGestureRecognizer(target: self, action: #selector(startAnimation))
viewButtonStart.addGestureRecognizer(gesture)
addSubview(viewButtonStart)
viewButtonStop.frame = CGRect(x: 120, y: 10, width: 100, height: 100)
viewButtonStop.backgroundColor = UIColor.yellowColor()
let gesture2 = UITapGestureRecognizer(target: self, action: #selector(stopAnimation))
viewButtonStop.addGestureRecognizer(gesture2)
addSubview(viewButtonStop)
viewShow.backgroundColor = UIColor.blueColor()
viewShow.frame = CGRect(x: screenWidth - 10 - 100, y: 10, width: 100, height: 100)
addSubview(viewShow)
isAnimationRunning = false
startAnimation()
startAnimation()
startAnimation()
}
func startAnimation()
{
print("startAnimation()")
if isAnimationRunning
{
stopAnimation()
}
// (*1) More data handling here...
isAnimationRunning = true
UIView.animateKeyframesWithDuration(
5,
delay: 0,
options: UIViewKeyframeAnimationOptions.CalculationModeLinear,
animations: animations(),
completion: completion())
}
func stopAnimation()
{
self.viewShow.layer.removeAllAnimations()
}
func animations() -> (() -> Void)
{
return {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: {
self.viewShow.alpha = 1
})
}
}
func completion() -> ((Bool) -> Void)?
{
return { (completed: Bool) in
print("animation completed(\(completed))")
if completed
{
self.isAnimationRunning = false
// (*2) More completion handling here....
}
}
}
アニメーションが開始するたびに、アニメーションが実行されているかどうかを確認して停止します。init 関数で startAnimation() を 3 回呼び出すと、最初の 2 つのアニメーションは停止するはずですが、停止しません。さらに悪いことに、アニメーションが終了してもすぐに完了関数が呼び出されません。この問題は、UIView.addKeyframeWithRelativeStartTime のプロパティが変更されていない場合にのみ発生します。この例で startAnimations() を数回呼び出すのは、そうでないように見えるかもしれませんが、実際には、さまざまな状況に応じてさまざまなアニメーションをセットアップして再起動します。
コンソールに表示される実際の結果は次のとおりです。
startAnimation()
startAnimation()
startAnimation()
animation completed(true)
animation completed(true)
animation completed(true)
私は次のようなものを期待していました:
startAnimation()
startAnimation()
animation completed(false)
startAnimation()
animation completed(false)
animation completed(true)
次の結果は私にも受け入れられます。
startAnimation()
animation completed(true)
startAnimation()
animation completed(true)
startAnimation()
animation completed(true)
or this:
startAnimation()
startAnimation()
startAnimation()
animation completed(false)
animation completed(false)
animation completed(true)
この問題により、(*1) と (*2) の両方で使用される変数が正しくなくなります。
助けや提案をいただければ幸いです、ありがとう