swiftmacoscocoansfontmanager

Get user selected NSFont using NSFontManager - Unable to override changefont function


I'm trying to allow the user to select a font of his/her choice using the NSFontManager. I could show the font picker using the following code

@IBAction func fontchangeclicked(_ sender: Any) {
            NSFontManager.shared.orderFrontFontPanel(nil)
    
        }

But the NSViewController is unable to recognise this overridden function.

override func changefont(_ sender: Any?) {
        guard let fontManager = sender as? NSFontManager else {
                    return
                }
                let newFont = fontManager.convert(self.globalfont)
                self.globalfont = newFont
       
               }

enter image description here


Solution

  • A list of requirements:

    1. It's changeFont instead of changefont.
    2. NSObject.changeFont(_:) is deprecated, use NSFontChanging.changeFont(_:) instead.
    3. The view controller must adopt NSFontChanging.
    4. Your changeFont(_:) is not called when the first responder object handles changeFont(_:).
    class ViewController: NSViewController, NSFontChanging {
    
        func changeFont(_ sender: NSFontManager?) {
            guard let fontManager = sender else {
                return
            }
            let newFont = fontManager.convert(self.globalfont)
            self.globalfont = newFont
        }
                   
    }