Disable/enable NSMenu item - swift

I've created a menu bar app, a NSMenu object using the Interface Builder (following this tutorial). The menu has two items:
Start Commando
Stop Commando
How can I disable/enable the menu items when they're clicked? I've set disabled "Auto Enables Items" and I can manually enable/disable the items in the Attributes inspector, but how can I achieve the same thing when their functions are called?
When "Start Commando" is clicked I want the item to disable and "Stop Commando" to enable. And the other way around when "Stop Commando" is clicked.

Swift provides with setEnabled property that can be used on NSMenuItem you are trying to enable or disable.
You can do the following :
#IBOutlet weak var startMenuItem: NSMenuItem!
startMenuItem.isEnabled = false or true

You can try below code :
let menu = NSMenu();
menu.autoenablesItems = false

As others say, there is a isEnabled property for NSMenuItems. One also needs to uncheck Auto Enables Items for that menu or sub-menu in the Attributes Inspector in Xcode, or through code, to allow the setting to take effect.
To get it to change on selection, in the IBAction called for the menu item, likely in your NSWindowController, do something like this:
#IBAction private func myMenuAction(sender: NSMenuItem) {
sender.isEnabled = false
}
You will not be able to then select the menu item afterwards. I assume you re-enable it else where as so:
if let appDelegate = NSApplication.shared.delegate as? AppDelegate {
appDelegate.myMenuItem.isEnabled = true
}
Code untested.

Declare a BOOL value for instance
BOOL isActive
if(isActive)
{
//show menu
}
else
{
//hide your menu
}
also make BOOL true when your view dismiss

Related

Access Menu Item to Disable/Enable

I would like to implement NSMenuItemto trigger certain functionality (e.g. "Run Calculation"). How do I access the menu items in order to enable/disable the items based on the app logic? E.g. the "cut" function for text is only enable as menu item when test is selected. "Run Calculation" should only get enabled when certain criteria are given.
Thanks!
You probably have some view controller or window controller that implements runCalculation, like this:
class ViewController: NSViewController {
#IBAction func runCalculation(_ sender: Any?) {
print(1 + 1)
}
}
And you have connected the “Run Calculation” menu item's action to the runCalculation method of the controller.
To enable and disable the menu item, follow these steps:
Make sure the “Calculator” menu itself (of type NSMenu) has the “Auto Enables Items” property turned on in IB, or has autoenablesItems set to true in code.
Make your controller conform to the NSUserInterfaceValidations protocol:
extension ViewController: NSUserInterfaceValidations {
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
// See step 3...
return true
}
}
In validateUserInterfaceItem, check whether the item's action is runCalculation(_:). If so, return true if and only if you want to allow the user to run the calculation:
extension ViewController: NSUserInterfaceValidations {
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(runCalculation(_:))?:
// Put your real test here.
return !textField.stringValue.isEmpty
default: return true
}
}
}

How do I keep NSMenuItem selected in a NSPopover with NSMenu?

I have a NSPopUpButton with a built up NSMenu.
However, when an NSMenuItem is selected, it keeps going back to the first item.
In this example, I'd expect "Maged" to be selected.
Any ideas?
Related question/answer: https://stackoverflow.com/a/53387962/157656
Duplicate:
It's been suggested that this is a duplicate of the question
How do I change/modify the displayed title of an NSPopUpButton
"I would like an NSPopUpButton to display a different title than the title of the menu item that is selected."
However, my question was about getting the NSPopUpButton to show the selected item.
In the end, I changed how I did it.
I am using a NSButton to show the menu and NSTextField to display the results.
If anyone is interested in the details, here they are.
Build the menu up and use .representedObject to store whatever you need to access at the other end. I used a struct with the name and code the in it.
You need to assign the NSMenu to the NSButton.menu
Then have a click, something like this.
#IBAction func changeVoiceClicked(_ sender: NSButton)
{
if let event = NSApplication.shared.currentEvent {
NSMenu.popUpContextMenu(sender.menu!, with: event, for: sender)
}
}
Your NSMenuItem should have an action on it, which using a selector points to a function.
Something like this:
#objc func voiceChanged(sender: NSMenuItem)
{
// cope will nil
var voice : VoiceDetail = VoiceDetail();
if (sender.representedObject != nil) {
voice = sender.representedObject as! VoiceDetail;
}
// Do what you need to on menu select.
// update text field.
}

How to create toggle button that only toggles once

I want to create a button that, when pressed, toggles to a different format and stays that way, not allowing the user to toggle it back. For example, I am trying to create a button that says "Special 1" then when it is clicked by the user, it toggles to say "USED". When the word "USED" pops up on the UIButton, it stays that way and the user cannot change it back. Please help me out I can't figure this out. I am also open to other ideas to execute this other then a UIButton, for example maybe a UITableView??
What you can do is create a boolean (true or false) variable in your ViewController, and whenever the button is tapped you set this variable so that the tap function associated with the button can be manipulated.
1.) Make an action connection from your ViewController to your code this can be done by clicking the dual view button (the two circles in the top right corner) then holding control and drag your button into your code. :
For more information on connecting views to your code: https://codewithchris.com/9-hooking-it-all-up-swift-iboutlet-properties/
Skip to 6 min for the actual connection.
2.) Now we can just make our boolean variable, and make a basic if statement:
var didClick:Bool = false
#IBAction func touchButton(_ sender: UIButton) {
if !didClick { // If didClick is false
didClick = true // Set it to true
sender.setTitle("USED", for: .normal)
}
}
Note: The sender should be set to UIButton NOT Any
Should look like this:
_ sender: UIButton
If you are using a storyboard you can write this inside the IBAction function:
#IBAction func buttonName(_ sender: UIButton) {
sender.isUserInteractionEnabled = false
// Do whatever you need to do after...
}
sender's type could be UIButton or Any depending on how you made the connection from the storyboard.

Menubar with Storyboard - validateMenuItem not get called

I'm trying to setup a menubar Application using storyboard but my validateMenuItem method not get called.
I will try to explain what i did.
First i dragged a Menu Item in my Application Scene. Then one Object for my MenuController. Created a MenuController (MenuController.swift) and filled it with code. Back in my storyboard I set my Menu delegate to MenuController and MenuController Outlet to Menu. (I'm not totally sure whether i have set the delegates correctly.)
When i start the app, the menu icon appears and the first item title is set to test. But when i'm clicking the icon the validateMenuItem method not get called.
MenuController.swift
import Cocoa
class MenuController: NSObject {
var statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
#IBOutlet weak var statusMenu: NSMenu!
#IBOutlet weak var item1: NSMenuItem!
override func awakeFromNib() {
print("awakeFromNib")
self.item1.title = "Test"
let icon = NSImage(named: "menubarIcon")
statusItem.image = icon
statusItem.menu = statusMenu
}
override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
print("validateMenuItem")
return true
}
}
Storyboard Menu Delegates
(source: picr.de)
Storyboard MenuController Delegates
(source: picr.de)
Has anybody an idea?
Greets from Austria!
The menu/UI validation mechanism does not query the menu's delegate but uses the item's target to determine the enabled state instead.
If the target is not explicitly set, it walks the responder chain.
To get basic validation, you have to make sure that the following things are setup:
"Auto Enables Items" is checked in Interface Builder (on by default)
You control-dragged the menu's action to the first responder
The menu's action is implemented in a class that is part of the responder chain (e.g. a view controller that manages a set of actions for your UI)
A basic implementation of validateUserInterfaceItem: could look like the following for an item with an action selector called test:
func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool
{
if anItem.action() == Selector("test:") {
print("validating item \(anItem)")
return true
}
return true
}

Disable a Button

I want to disable a button (UIButton) on iOS after it is clicked. I am new to developing for iOS but I think the equivalent code on objective - C is this:
button.enabled = NO;
But I couldn't do that on swift.
The boolean value for NO in Swift is false.
button.isEnabled = false
should do it.
Here is the Swift documentation for UIControl's isEnabled property.
If you want the button to stay static without the "pressed" appearance:
// Swift 2
editButton.userInteractionEnabled = false
// Swift 3
editButton.isUserInteractionEnabled = false
Remember:
1) Your IBOutlet is --> #IBOutlet weak var editButton: UIButton!
2) Code above goes in viewWillAppear
The way I do this is as follows:
#IBAction func pressButton(sender: AnyObject) {
var disableMyButton = sender as? UIButton
disableMyButton.enabled = false
}
The IBAction is connected to your button in the storyboard.
If you have your button setup as an Outlet:
#IBOutlet weak var myButton: UIButton!
Then you can access the enabled properties by using the . notation on the button name:
myButton.enabled = false
Disable a button on Swift 3:
yourButton.isEnabled = false
For those who Googled "disable a button" but may have more nuanced use cases:
Disable with visual effect: As others have said, this will prevent the button from being pressed and the system will automatically make it look disabled:
yourButton.isEnabled = false
Disable without visual effect: Are you using a button in a case where it should look normal but not behave likes button by reacting to touches? Try this!
yourButton.userInteractionEnabled = false
Hide without disabling: This approach hides the button without disabling it (invisible but can still be tapped):
yourButton.alpha = 0.0
Remove: This will remove the view entirely:
yourButton.removeFromSuperView()
Tap something behind a button: Have two buttons stacked and you want the top button to temporarily act like it's not there? If you won't need the top button again, remove it. If you will need it again, try condensing its height or width to 0!
Swift 5 / SwiftUI
Nowadays it's done like this.
Button(action: action) {
Text(buttonLabel)
}
.disabled(!isEnabled)
You can enable/disable a button using isEnabled or isUserInteractionEnabled property.
The difference between two is :
isEnabled is a property of UIControl (super class of UIButton) and it has visual effects (i.e. grayed out) of enable/disable
isUserInteractionEnabled is a property of UIView (super class of UIControl) and has no visual effect although but achieves the purpose
Usage :
myButton.isEnabled = false // Recommended approach
myButton.isUserInteractionEnabled = false // Alternative approach
Let's say in Swift 4 you have a button set up for a segue as an IBAction like this #IBAction func nextLevel(_ sender: UIButton) {}
and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:
var appMode = 0
#IBAction func mySegue(_ sender: UIButton) {
if appMode == 1 { // avoid crash if button pressed during other app actions and/or conditions
let conflictingAction = sender as UIButton
conflictingAction.isEnabled = false
}
}
Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.
The button can be Disabled in Swift 4 by the code
#IBAction func yourButtonMethodname(sender: UIButon) {
yourButton.isEnabled = false
}
in order for this to work:
yourButton.isEnabled = false
you need to create an outlet in addition to your UI button.
Building on other answers here. I wanted to disable button for a few seconds to prevent double taps. Swift 5 version, xcode 13.4.1 likes this and has no warnings or errors.
#IBAction func saveComponent(_ sender: Any) {
let myButton = sender as? UIButton
myButton?.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2000))
{
myButton?.isEnabled = true
}
}