4

The following code works perfect in my sandbox:

@IBAction func filterClicked(sender: NSButton) {
  println(sender.state)
  if let clickEvent = NSApp.currentEvent! {
    if Int(clickEvent.modifierFlags.rawValue) & Int(NSEventModifierFlags.ControlKeyMask.rawValue) != 0 {
      if sender.state == NSOffState {
        sender.state == NSOnState
      }
    }
  }
  println(sender.state)
}

The connected button is an On-Off button. So when it's on and I ctrl-click it it will stay on.

Unfortunately in my app where I really need this it does not work. I checked that in both sandbox and prod app the bindings/settings are identically for both buttons. The debugger shows that

        sender.state == NSOnState

is simply not performed. state stays NSOffState. Gnawing my keyboard did not help. Any idea?

qwerty_so
  • 35,448
  • 8
  • 62
  • 86

4 Answers4

6

You are not assign any value to the button state.

sender.state = NSOnState

Update for Swift 4.2

sender.state = NSControl.StateValue.on
Ashutosh Shukla
  • 358
  • 5
  • 14
Superolo
  • 98
  • 6
1

Changing state of a Radio Button (Check state) for swift 4:

@IBOutlet weak var checkedButton: NSButton!

checkedButton.state = NSControl.StateValue.off // State = off

checkedButton.state = NSControl.StateValue.on  // State = on
MAhipal Singh
  • 4,745
  • 1
  • 42
  • 57
0

I know this already has an accepted answer, but sharing my scenario in case it trips up someone else:

I had the same issue where I couldn't programmatically set the state for my button in a custom table view cell. MY issue, is that I was trying to set the state when my table first created the cell. Instead, I had to make sure to override the layout method in my custom cell and set the state there.

ghostatron
  • 2,620
  • 23
  • 27
0

I had this in a CollectionViewItem... I had an outlet for the favouriteButton...

class PictureCollectionViewItem: XCollectionViewItem
{
    @IBOutlet var thumbnailView: NSImageView!
    @IBOutlet var tagsView: NSTextField!
    @IBOutlet var favouriteButton: NSButton!
    ... 
}

I had linked the outlet to the Collection View Item object

but NOT linked it to the File's Owner...

As soon as I linked it to the File's Owner as well, ... it all worked.