ios - 在 iOS 中等待 50 个运行循环周期

标签 ios swift grand-central-dispatch

我想等待运行循环运行并且屏幕渲染 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/

相关文章:

iphone - 创建指向对象的指针后删除对象 [Objective-C]

ios - 通过一次滑动手势快速控制多个按钮

ios - 如何使用自动布局以编程方式快速设置旋转时 UICollectionView 的宽度

ios - 在Swift中“暂停”游戏

ios - 在异步工作完成之前关闭返回数据

ios - 如何在授予位置权限后执行任务 ios

ios - 以编程方式将数据从一个 View Controller 传递到现有 View Controller

iphone - iOS 键盘和自定义按钮

ios - IBM Worklight - Dojo Video 小部件在 iOS 设备中无法工作

ios - 放大 ScrollView