我想等待运行循环运行并且屏幕渲染 50 次后再执行操作。
是否有必要使用CAMediaTiming
和计数器?有没有办法直接挂接到 NSRunLoop
?我可以像这样使用 50 个嵌套 DispatchQueue.async
调用来实现此目的吗?
import Dispatch
func wait(ticks: UInt, queue: DispatchQueue = DispatchQueue.main, _ handler: @escaping () -> Void) {
var ticks = ticks
func predicate() {
queue.async {
ticks -= 1
if ticks < 1 {
handler()
return
}
queue.async(execute: predicate)
}
}
predicate()
}
编辑:如果有人想知道,该代码片段确实有效,并且当我们谈论应用程序运行循环时它表现得非常好。
最佳答案
您可以使用CADisplayLink,每次屏幕更新都会调用它。
let displayLink = CADisplayLink(target: self, selector: #selector(drawFunction(displayLink:)))
displayLink.add(to: .main, forMode: .commonModes)
在drawFunction(或谓词等)中,我们可以从刻度中减去。当它们达到 0 时,我们已经到达第 50 帧并使 displayLink 无效。
var ticks = 50
@objc private func drawFunction(displayLink: CADisplayLink) {
doSomething()
ticks -= 1
if ticks == 0 {
displayLink.invalidate()
displayLink = nil
return
}
}
CADisplayLink 还可以提供帧之间的时间量。类似的讨论可以找到here 。如果您关心这里的绝对准确性,您可以计算帧之间的时间。来自文档:
The duration property provides the amount of time between frames at the maximumFramesPerSecond. To calculate the actual frame duration, use targetTimestamp - timestamp. You can use this value in your application to calculate the frame rate of the display, the approximate time that the next frame will be displayed, and to adjust the drawing behavior so that the next frame is prepared in time to be displayed.
关于ios - 在 iOS 中等待 50 个运行循环周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325788/