2016-05-14 62 views
1

我有一個顯示自定義不確定進度指示器的類。每個計時器更新它只需使用CGAffineTransformRotate遞增UIImageView的旋轉。更好的替代基於計時器的自定義活動指標的動畫?

但是,這一切都有效,我注意到它在運行時,它正在等待的後臺進程運行速度降低了50% - 這是一個巨大的懲罰。例如;而不是說20秒完成處理需要30秒。有人可以推薦性能較低的解決方案嗎?

func show() { 
    timer?.invalidate() 
    timer = NSTimer.scheduledTimerWithTimeInterval(0.03, target: self, selector: #selector(self.updateTimer(_:)), userInfo: nil, repeats: true) 
} 

func updateTimer(sender: NSTimer) { 
    iconView.transform = CGAffineTransformRotate(iconView.transform, 0.15) 
} 
+1

你真的需要33幀/秒嗎? – rmaddy

+1

這是什麼圖像?你可以使用核心動畫?你可以使用視頻嗎? – jtbandes

+1

另外,儀器在哪裏說CPU正在用掉? – jtbandes

回答

1

使用的Core Animation動畫旋轉。窗口服務器將完成應用程序進程之外的所有工作。

let animation = CABasicAnimation(keyPath: "transform.rotation") 
animation.fromValue = 0 
animation.toValue = 2 * M_PI 
animation.repeatCount = .infinity 
animation.duration = 1.25 
iconView.layer.addAnimation(animation, forKey: animation.keyPath) 
+0

謝謝你的男人! –

0

我認爲你可以使用dispatch_source從@羅布的回答是:

Do something every x minutes in Swift

下面是代碼:

var timer: dispatch_source_t! 

func startTimer() { 
    let queue = dispatch_queue_create("com.domain.app.timer", nil) 
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) 
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 60 * NSEC_PER_SEC, 1 * NSEC_PER_SEC) // every 60 seconds, with leeway of 1 second 
    dispatch_source_set_event_handler(timer) { 
     // do whatever you want here 
    } 
    dispatch_resume(timer) 
} 

func stopTimer() { 
    dispatch_source_cancel(timer) 
    timer = nil 
}