簡體   English   中英

使用標簽欄控制器更改視圖時,UIView.animateWithDuration完成得太早

[英]UIView.animateWithDuration completes too early when changing view with Tab Bar Controller

我通過增加一個簡單的圖像來制作進度條:

let progressBar = createProgressBar(width: self.view.frame.width, height: 60.0)
let progressBarView = UIImageView(image: progressBar)
progressBarView.frame = CGRect(x: 0, y: 140, width: 0, height: 60)
UIView.animateWithDuration(60.0, delay: 0.0, options: [], animations: {
    progressBarView.frame.size.width = self.backgroundView.frame.size.width
    }, completion: {_ in
        print("progress completed")
    }
)

這按預期工作,但使用TabBarController更改視圖時出現問題。 更改視圖時,我希望進度條在后台繼續進行動畫處理,以便我可以返回到該視圖以檢查進度,但是當我更改視圖時,它確實會立即結束,並調用完成塊。

為什么會發生這種情況,以及如何解決?

當您點擊另一個tabBar項目時,正在執行動畫的viewController將處於viewDidDisappear狀態,並且動畫將被刪除。

實際上,不建議在屏幕前面未顯示viewController時執行任何動畫。

要繼續中斷的動畫進度,您必須保持動畫的當前狀態,並在tabBar項切換回時恢復它們。

例如,您可以保存一些實例變量以保留動畫的持續時間,進度,beginWidth和endWidth。 您可以在viewDidAppear恢復動畫:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    // `self.duration` is the total duration of the animation. In your case, it's 60s.
    // `self.progress` is the time that had been consumed. Its initial value is 0s.
    // `self.beginWidth` is the inital width of self.progressBarView.
    // `self.endWidth`, in your case, is `self.backgroundView.frame.size.width`.

    if self.progress < self.duration {

        UIView.animateWithDuration(self.duration - self.progress, delay: 0, options: [.CurveLinear], animations: {

            self.progressBarView.frame.size.width = CGFloat(self.endWidth)
            self.beginTime = NSDate() // `self.beginTime` is used to track the actual animation duration before it interrupted.

            }, completion: { finished in
                if (!finished) {
                    let now = NSDate()
                    self.progress += now.timeIntervalSinceDate(self.beginTime!)
                    self.progressBarView.frame.size.width = CGFloat(self.beginWidth + self.progress/self.duration * (self.endWidth - self.beginWidth))
                } else {
                    print("progress completed")
                }
            }
        )
    }
}

暫無
暫無

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

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