簡體   English   中英

UIView動畫和UIButton停止按b / c正常工作-迅速4

[英]UIView Animation and UIButton stop working b/c Home pressed - Swift 4

我有一個執行“呼吸動畫”的playButton 當我按下該按鈕時,它的效果很好。 如果我按設備的“主頁”按鈕,然后重新打開應用程序,則會出現問題。 重新打開后, playButton沒有“呼吸動畫”,並且不起作用(按下時什么也沒有發生)。

@IBOutlet weak var playButton: UIButton!

override func viewWillAppear(_ animated: Bool) {

    UIView.animate(withDuration: 1.0,
                   delay: 0,
                   options: [.autoreverse, .repeat, .allowUserInteraction],
                   animations: {
                    self.playButton.transform = CGAffineTransform(scaleX: 1.175, y: 1.175)
    },
                   completion: nil

    )

 }

我已經在以前的游戲應用程序中處理過此問題,如果用戶按下“主頁”按鈕或出現中斷(來電),我需要保存並暫停游戲。 因此,我很清楚:

func applicationDidBecomeActive() {}

func applicationWillResignActive() {}

func applicationDidEnterBackground() {}

但是,我沒有處理gameState,計時器,需要保存數據等問題。我只是希望在按下Home按鈕后重新打開應用程序時,我的按鈕及其動畫可以正常工作。

我也嘗試使用override func viewDidLayoutSubviews() {}代替viewWillAppear 但這沒有用。

首先,如果在同一個ViewController (VC)中有多個動畫,這些動畫在按下playButton之后發生,那么這可以解釋為什么從背景返回時將其禁用的原因。 為什么? 我不知道。 但是我遇到了類似的問題,並通過為最初設置為在按下UIButton時發生的多個動畫創建新的class和VC來解決了該問題。 在按鈕的IBAction ,我只是為新的VC創建了一個序列。

關於動畫,您可以采用以下兩種方法:1)使用CALayer暫停和恢復動畫;或2)只需使用NotificationCenter,甚至無需觸摸任何AppDelegate代碼。 我更喜歡簡單的方法,因為它可以節省時間和精力。 因此,請在將出現按鈕動畫的VC中嘗試以下代碼:

override func viewWillAppear(_ animated: Bool) {

    NotificationCenter.default.addObserver(self, selector:#selector(goingToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector:#selector(openingApp), name: UIApplication.willEnterForegroundNotification, object: nil)



    UIView.animate(withDuration: 1.0,
                    delay: 0,
                    options: [.autoreverse, .repeat, .allowUserInteraction],
                    animations: {
                        self.playButton.transform = CGAffineTransform(scaleX: 1.175, y: 1.175)
                    },
                    completion: nil)
}

@objc func goingToBackground(){
    playButton.transform = .identity
}

@objc func openingApp(){
    self.view.layoutIfNeeded()
    UIView.animate(withDuration: 1.0,
                   delay: 0.3,
                   options: [.autoreverse, .repeat, .allowUserInteraction],
                   animations: {
                    self.playButton.transform = CGAffineTransform(scaleX: 1.175, y: 1.175)}, completion: nil)
    self.view.layoutIfNeeded()

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM