在 运行 时间更改调度程序的时间间隔

Change time interval of scheduler at run time

代码如下:

import Cocoa
import Foundation

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        lbl.drawsBackground = true
        lbl.backgroundColor = NSColor.black
        Timer.scheduledTimer(withTimeInterval: 1.0/Double(hz * 2), repeats: true, block: toggleBackground)
    }

    var hz = 40

    func toggleBackground(_ timer: Timer) {
        if lbl.backgroundColor == NSColor.white{
            lbl.backgroundColor = NSColor.black
        } else {
            lbl.backgroundColor = NSColor.white
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


    @IBOutlet weak var lbl: NSTextField!
}

完整项目在这里:https://github.com/kindlychung/Flickalz

这是一个简单的应用程序,可以以 80Hz 的频率更改标签的背景颜色。我想在 运行 时间自定义该频率(通过文本字段或滑块),但不知道如何实现。有什么想法吗?

您可以尝试将 UISlider 放入您的第一个 UIViewController

然后,按照本教程进行操作:http://sourcefreeze.com/ios-slider-uislider-example-using-swift/

诀窍是使计时器无效并重新安排:

import Cocoa
import Foundation

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    @IBOutlet weak var freqFld: NSTextField!

    @IBAction func setFreq(_ sender: NSButton) {
        restartTimer(freqFld.integerValue)
    }


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        window.backgroundColor = NSColor.black
    }

    var timer: Timer = Timer()

    func restartTimer(_ hz: Int) {
        timer.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 1.0/Double(hz * 2), repeats: true, block: toggleBackground)
    }

    override init() {
        super.init()
        restartTimer(40)
    }

    func toggleBackground(_ timer: Timer) {
        if window.backgroundColor == NSColor.white{
            window.backgroundColor = NSColor.black
        } else {
            window.backgroundColor = NSColor.white
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}

完整的项目可以在这里找到:https://github.com/kindlychung/Flickalz