Skip to content

Instantly share code, notes, and snippets.

@revblaze
Last active April 6, 2020 23:02
Show Gist options
  • Save revblaze/542fd2347bdb23131f74ba68e3fcebe4 to your computer and use it in GitHub Desktop.
Save revblaze/542fd2347bdb23131f74ba68e3fcebe4 to your computer and use it in GitHub Desktop.
Protocols & Delegation in Swift (Sample)
protocol Customizable {
func hideMenu()
func isDarkModeActive()
func setDarkMode(_ mode: Bool)
}
class MenuViewController: NSViewController {
weak var delegate: Customizable?
override func viewDidLoad() {
super.viewDidLoad()
let mode = delegate?.isDarkModeActive()
delegate?.setDarkMode(mode)
}
@IBAction func closeMenuAction(_ sender: NSButton) {
delegate?.hideMenu()
}
...
}
class ViewController: NSViewController, Customizable {
@IBOutlet var menuView: NSView!
let menuController = MenuViewController()
override func viewDidLoad() {
super.viewDidLoad()
menuController.delegate = self
}
func hideMenu() {
menuView.isHidden = true
}
func setDarkMode(_ mode: Bool) {
let darkMode = NSAppearance(named: .darkAqua)
let lightMode = NSAppearance(named: .aqua)
if mode { NSApplication.shared.appearance = darkMode }
else { NSApplication.shared.appearance = lightMode }
}
func isDarkModeActive() -> Bool {
if InterfaceStyle() == .Dark { return true }
else { return false }
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment