ios - 从同一范围调用 block /闭包

标签 ios swift timer closures

我正在创建一个屏幕在黑白之间快速切换的应用程序。为此,我使用了一个 Timer

我的问题归结为无法在计时器声明中从相同范围 (changeBackgroundColor) 调用函数。

let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: changeBackgroundColor) 
//Error: 'Cannot convert value of type '(ViewController) -> (Timer) -> Void' to expected argument type '(Timer) -> Void'

func changeBackgroundColor(timer: Timer) -> Void {
    //change the color of the screen (not the issue here)
}

我以为我已经理解了闭包,但这里的作用域似乎有问题。

最佳答案

使用计时器“ block ”版本的全部意义在于避免必须创建单独的函数。

你应该这样写:

let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
    // change the color of the screen
}

关于ios - 从同一范围调用 block /闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44706105/

相关文章:

ios - 如何在 CNContact 中快速查看联系人来源?

ios - UILabel 仅支持某些 Unicode 字符

swift - 在调用方法之前添加 subview

java - 从另一个线程内调用 TimerTask 是线程安全的

java - Android TextView 计时器

ios - SwiftUI:minimumScaleFactor 没有均匀地应用于堆栈元素

ios - 如何在 MKMapView 上显示文本

javascript - iPad 2 上的 Safari 动态加载图像导致内存泄漏

ios - 当应用程序返回前台时读取最新的推送通知数据(不是通过点击通知)

c# - 轮询窗口服务的计时器