SwiftUI: How can I open up a Font Picker?

Viewed 741

I am writing a simple Status Bar app with a single popup, using SwiftUI.

Is it possible to launch the font picker from a button in the popup view and to capture the results?

The app runs on MacOS. I have XCode 11.7

1 Answers

I had the same question and eventually found this repo, which provides a FontPicker component. I attach the relevant part of the code below which shows how to NSFontPanel in SwiftUI.

class FontPickerDelegate {
    var parent: FontPicker

    init(_ parent: FontPicker) {
        self.parent = parent
    }
    
    @objc
    func changeFont(_ id: Any ){
        parent.fontSelected()
    }

}

public struct FontPicker: View {
    let labelString: String
    @Binding var font:NSFont
    
    @State var fontPickerDelegate:FontPickerDelegate? = nil
    
    public init(_ label: String, selection: Binding<NSFont>) {
        self.labelString = label
        self._font = selection
    }
    public var body: some View {
        HStack {
            Text(labelString)
            Button(action: {
                if NSFontPanel.shared.isVisible {
                    NSFontPanel.shared.orderOut(nil)
                    return
                }
                self.fontPickerDelegate = FontPickerDelegate(self)
                NSFontManager.shared.target = self.fontPickerDelegate
                NSFontPanel.shared.setPanelFont(self.font, isMultiple: false)
                NSFontPanel.shared.orderBack(nil)
            }, label: {
                Image(systemName: "textformat").resizable().scaledToFit()
            })
        }
    }
    
    func fontSelected() {
        self.font = NSFontPanel.shared.convert(self.font)
        //NSFontPanel.shared.orderOut(nil)
    }
}
Related