以下是代码:
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下更改标签的背景颜色。我想在运行时使频率可以自定义(通过文本字段或滑块),但不知道如何完成。有什么想法吗?
答案 0 :(得分:1)
诀窍是使计时器无效并重新计算:
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
答案 1 :(得分:0)
您可以尝试将UISlider
放入第一个UIViewController
。
然后,请按照本教程:http://sourcefreeze.com/ios-slider-uislider-example-using-swift/