残念ながら、アプリをホームスクリーンに最小化してからフォアグラウンドに戻すと、UIView.animateWithDuration
が停止することがわかりました。animateWithDurationを再開するフォアグラウンドに戻った後に返す
私は最後の1時間を(バックグラウンド/フォアグラウンド切り替えを検出することによって)解決する方法を見つけ出し、オブザーバを追加しました。私はそれを行い、コンソールでデバッグメッセージで正常に検出しました。しかし、私は私の視点でアニメーションを再開する方法については確信しています。アプリをフォアグラウンドに戻したときにアニメーションを一時停止/再開、または再起動する正しい方法は何ですか?
ViewController.swift
class ViewController: UIViewController {
func cameBackFromSleep(sender : AnyObject) {
// Restart animation here or resume?
print ("If you can see this, congrats... observer works :-)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Observer to detect return from background
NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(ViewController0.cameBackFromSleep(_:)), name: UIApplicationDidBecomeActiveNotification, object: nil )
// Add a label
let label = UILabel(frame: CGRectMake(0, 600 , 200, 200))
label.text = "test message"
label.font = UIFont.boldSystemFontOfSize(12)
label.sizeToFit()
self.view.addSubview(label)
// Animation to move label
func animateText() {
UIView.animateWithDuration(2.0, delay: 0.0, options: [ .Autoreverse, .Repeat, .CurveEaseInOut, .BeginFromCurrentState], animations: {
label.alpha = 0.3
label.frame.origin.x = ((global.maxwidth/2) * -1)
}, completion: { finished in
if finished {
label.frame.origin.x = 0.0
}
})
}
// This guy here stops once you minimize the app to background
animateText()
}
}
私はSwift/iOS開発が初めてです。 'comeBackFromSleep()'は 'viewDidLoad()'のスコープの外にあるので 'viewDidLoad()'の中に 'animateText()'をどのように呼び出すのですか? – theflarenet
'func animateText()'を外に出す必要があります。 'viewDidLoad()'が外にあります。そうすれば、他の方法からアクセスすることができます。したがって、 'viewDidLoad()'の下に 'func animateText()'を置き、 'comeBackFromSleep()'に 'animateText()'とタイプしてください。 – Lawrence413
私はそれが簡単な解決策であると考えましたが、私の実際のアニメーション機能には、既に開始されたビュー内のラベルの幅に依存する他の変数があります。私の唯一の解決策は、アプリケーションをフォアグラウンドに戻すたびに何らかの方法でラベルを削除し、ビューをアニメーションでもう一度追加することです。 – theflarenet