Actionable NSMenuItems for Time-ato

Hello!

As a challenge to Chapter 9 (Adding your own tasks), I wanted to add the possibility to start any task by clicking on it. (I don’t know the pomorodo method, it’s just for the challenge’s sake)

I think I am able to create the action, but it never seems to be enabled. Is there a restriction on using storyboard+code for menu items?

Here’s the code to add the action (in MenuManager, in the loop to create all the tasks items):

item.isEnabled = true
item.action = #selector(onTaskSelection(taskID:))

The action

@objc func onTaskSelection(taskID: UUID) {
    guard let task = taskManager.tasks.first(where: { $0.id == taskID }) else {
        return
    }
    taskManager.start(task: task)
}

Note that I use the UUID instead of the task itself because Task is struct and the function needs to be declared as @objc.

I feel like I’m missing something obvious… any pointer is welcome!

This is tricker than I expected.

At first I thought it would be solved by setting the menu items’s target to self but that wasn’t enough.

If using plain text menu items, it works.
I used this to create the menu items:

let item = NSMenuItem(
  title: task.title,
  action: #selector(onTaskSelection(_:)),
  keyEquivalent: "")
item.target = self

And set up the selector like this:

@objc func onTaskSelection(_ sender: NSMenuItem) {
  print(sender.title)
}

But I couldn’t make this work with a custom view.

I would approach this by adding a transparent button to TaskView that filled the view and was on top of everything else. It would post a notification when clicked, setting the view’s task as the notification object.

1 Like

Thank you so much for the reply!

Yeah, it’s a bummer that it doesn’t work with a custom view, but on the other hand, I understand why. It could get out of hands quickly, with weird images and behaviours.

I was able to make it work with the button, but it doesn’t highlight on mouse hover.

¯\(ツ)/¯ At least I learned a ton in the process!

Thank you for the help!

1 Like