简体   繁体   English

SwiftUI:如何打开字体选择器?

[英]SwiftUI: How can I open up a Font Picker?

I am writing a simple Status Bar app with a single popup, using SwiftUI.我正在使用 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.该应用程序在 MacOS 上运行。 I have XCode 11.7我有 XCode 11.7

I had the same question and eventually found this repo , which provides a FontPicker component.我有同样的问题,最终找到了这个 repo ,它提供了一个 FontPicker 组件。 I attach the relevant part of the code below which shows how to NSFontPanel in SwiftUI.我附上了下面代码的相关部分,它显示了如何在 SwiftUI 中使用 NSFontPanel。

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM