|
| 1 | +import AppKit |
| 2 | +import Foundation |
| 3 | +import Preferences |
| 4 | +import SwiftUI |
| 5 | + |
| 6 | +public struct FontPicker: View { |
| 7 | + @Binding var font: NSFont |
| 8 | + @State var fontManagerDelegate: FontManagerDelegate? |
| 9 | + |
| 10 | + public init(font: Binding<NSFont>) { |
| 11 | + _font = font |
| 12 | + } |
| 13 | + |
| 14 | + public var body: some View { |
| 15 | + Button { |
| 16 | + if NSFontPanel.shared.isVisible { |
| 17 | + NSFontPanel.shared.orderOut(nil) |
| 18 | + } |
| 19 | + |
| 20 | + self.fontManagerDelegate = FontManagerDelegate(font: font) { |
| 21 | + self.font = $0 |
| 22 | + } |
| 23 | + NSFontManager.shared.target = self.fontManagerDelegate |
| 24 | + NSFontPanel.shared.setPanelFont(self.font, isMultiple: false) |
| 25 | + NSFontPanel.shared.orderBack(nil) |
| 26 | + } label: { |
| 27 | + HStack { |
| 28 | + Text(font.fontName) |
| 29 | + + Text(" - ") |
| 30 | + + Text(font.pointSize, format: .number.precision(.fractionLength(1))) |
| 31 | + + Text("pt") |
| 32 | + |
| 33 | + Spacer().frame(width: 30) |
| 34 | + |
| 35 | + Image(systemName: "textformat") |
| 36 | + .frame(width: 13) |
| 37 | + .scaledToFit() |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + final class FontManagerDelegate: NSObject { |
| 43 | + let font: NSFont |
| 44 | + let onSelection: (NSFont) -> Void |
| 45 | + init(font: NSFont, onSelection: @escaping (NSFont) -> Void) { |
| 46 | + self.font = font |
| 47 | + self.onSelection = onSelection |
| 48 | + } |
| 49 | + |
| 50 | + @objc func changeFont(_ sender: NSFontManager) { |
| 51 | + onSelection(sender.convert(font)) |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +public extension FontPicker { |
| 57 | + init(font: Binding<StorableFont>) { |
| 58 | + _font = Binding( |
| 59 | + get: { font.wrappedValue.nsFont }, |
| 60 | + set: { font.wrappedValue = StorableFont(nsFont: $0) } |
| 61 | + ) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +#Preview { |
| 66 | + FontPicker(font: .constant(.systemFont(ofSize: 15))) |
| 67 | + .padding() |
| 68 | +} |
| 69 | + |
0 commit comments