2016-04-30 15 views
0

残念ながら、アプリをホームスクリーンに最小化してからフォアグラウンドに戻すと、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() 
    } 
} 

答えて

1

comeBackFromSleep(_:)animateText()を置きます。私はアニメーションを再開するのはちょっと難しいと思うので、それを再開するだけです。

行動多少(あなたがAppDelegateの方法で自分を見てとることができます)このために理にかなって:

func applicationDidBecomeActive(application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

それはあなたが(アニメーションを含みます)UIを更新する必要があると述べています。したがって、アプリケーションをバックグラウンドに置いた後にアニメーションが停止するのは正常な動作です。

+0

私はSwift/iOS開発が初めてです。 'comeBackFromSleep()'は 'viewDidLoad()'のスコープの外にあるので 'viewDidLoad()'の中に 'animateText()'をどのように呼び出すのですか? – theflarenet

+0

'func animateText()'を外に出す必要があります。 'viewDidLoad()'が外にあります。そうすれば、他の方法からアクセスすることができます。したがって、 'viewDidLoad()'の下に 'func animateText()'を置き、 'comeBackFromSleep()'に 'animateText()'とタイプしてください。 – Lawrence413

+0

私はそれが簡単な解決策であると考えましたが、私の実際のアニメーション機能には、既に開始されたビュー内のラベルの幅に依存する他の変数があります。私の唯一の解決策は、アプリケーションをフォアグラウンドに戻すたびに何らかの方法でラベルを削除し、ビューをアニメーションでもう一度追加することです。 – theflarenet

関連する問題