swiftnsmenunsmenuitemnsevent

Swift: How can I update NSMenuItem while it is active (visible)?


I created a simple timer which updates a counter within a NSMenuItem.

func timerUpdate(){
    dispatch_async(dispatch_get_main_queue()){

        // calculating time
        let timeLeft = self.lxTimeLeft() // returns a double of remaining seconds
        let hoursLeft = Int(timeLeft/3600)
        let minLeft = Int(timeLeft/60) - (hoursLeft*60)
        let secLeft = Int(timeLeft) - (hoursLeft*3600) - (minLeft*60)

        let hoursLeftStr = String(format:"%02d", hoursLeft)
        let minLeftStr = String(format:"%02d", minLeft)
        let secLeftStr = String(format:"%02d", secLeft)

        println("timeLeft \(hoursLeftStr):\(minLeftStr):\(secLeftStr)")
        self.menuActiveFor.title = "\(self.activatedFor) \(hoursLeftStr):\(minLeftStr):\(secLeftStr)h"

        self.statusMenu.update() // not working
    }
}

Basically it works, but when I open the NSMenu it won't refresh the NSMenuItem (UI). I found a solution for Objective-C (How to update NSMenu while it's open?) but sadly, I am not able to adapt this using Swift.


Solution

  • You need to read the docu about NSRunLoop when your menu is displayed none of your threads will get control. You need to tell the OS you want to participate.