Search code examples
macoscocoaappkit

How to observe changes in system preference "Sidebar icon size" in AppKit?


In the Main section of the System Preferences of macOS, the user can change the "Sidebar icon size". This setting changes the icon size (and since macOS 11 also the font size) used in Sidebars, when the size mode of the NSOutlineView in question is set to default.

I want to add an UserNotification observer in my app to track changes to the said setting, so I can perform some additional finetuning after each size change, but could not find any applicable NSNotification.Name or other constant.

Any workable solution or suggestion is welcome.


Solution

  • I knew I had a solution for this, but I was searching in the wrong projects. This is what I found. Observing UserDefaults is not a fantastic option, but at least it works:

    fileprivate let tableViewDefaultSizeModeKey = "NSTableViewDefaultSizeMode"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.addObserver(self, forKeyPath: tableViewDefaultSizeModeKey, options: .new, context: nil)
    }
    
    deinit {
        UserDefaults.standard.removeObserver(self, forKeyPath: tableViewDefaultSizeModeKey)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == tableViewDefaultSizeModeKey {
            // Do whatever is needed
        }
    }