Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftiff/5093b08d67a21559fbd78621a4211dbf to your computer and use it in GitHub Desktop.
Save ftiff/5093b08d67a21559fbd78621a4211dbf to your computer and use it in GitHub Desktop.
How to enable a button if one or more checkbox is selected
//
// EnableButtonIfAtLeastOneCheckboxIsSelected.swift
// SplashBuddy
//
// Created by François Levaux on 23.05.17 (Swift 3)
// Copyright © 2017 François Levaux-Tiffreau. All rights reserved.
//
// Create 5 checkboxes & link them to this file
// Create one button, bind "Enabled" to "Enable Button If At Least One Checkbox Is Selected"
// with Model Key Path set to "self.atLeastOneSelectedButton"
//
// tl;dr use "directory1Button.cell.state"
import Cocoa
class EnableButtonIfAtLeastOneCheckboxIsSelected: NSViewController {
@IBOutlet weak var directory1Button: NSButton!
@IBOutlet weak var directory2Button: NSButton!
@IBOutlet weak var directory3Button: NSButton!
@IBOutlet weak var directory4Button: NSButton!
@IBOutlet weak var directory5Button: NSButton!
// Register Dependent Keys
// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVODependentKeys.html
dynamic class func keyPathsForValuesAffectingAtLeastOneSelectedButton() -> Set<String> {
return ["directory1Button.cell.state",
"directory2Button.cell.state",
"directory3Button.cell.state",
"directory4Button.cell.state",
"directory5Button.cell.state"]
}
dynamic var atLeastOneSelectedButton: Bool {
return self.compileDirectoryButtons().contains(where: { $1 == true })
}
private func intToBool(_ int: Int) -> Bool {
return int == NSOnState ? true : false
}
private dynamic func compileDirectoryButtons() -> Dictionary<String, Bool> {
var result = Dictionary<String, Bool>()
result["directory1"] = intToBool(self.directory1Button.state)
result["directory2"] = intToBool(self.directory2Button.state)
result["directory3"] = intToBool(self.directory3Button.state)
result["directory4"] = intToBool(self.directory4Button.state)
result["directory5"] = intToBool(self.directory5Button.state)
return result
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment