我想使用 SwiftUI View 在 macOS (Ventura) 上打印标签之类的东西。但这会导致一张白纸:
func startPrinting() {
let printView = NSHostingView(rootView: Text("I want to print"))
printView.frame.size = CGSize(width: 200, height: 200)
let printInfo = NSPrintInfo()
printInfo.topMargin = 0
printInfo.leftMargin = 0
printInfo.bottomMargin = 0
printInfo.rightMargin = 0
let printOperation = NSPrintOperation(view: printView, printInfo: printInfo)
printOperation.run()
}
当我将
Text
切换到TextField
时,会打印出来,但我不知道为什么。
如何打印 SwiftUI 视图?
我还想打印 SwiftUI 视图。就我而言,是带注释的地图视图。网上好像没有太多建议。我添加了提供的函数来尝试使用 Xcode 14 和 Xcode 15 打印 ContentView,结果类似,但没有完整的解决方案。
import SwiftUI
func startPrinting() {
let printView = NSHostingView(rootView: ContentView())
printView.frame.size = CGSize(width: 200, height: 200)
let printInfo = NSPrintInfo()
printInfo.topMargin = 0
printInfo.leftMargin = 0
printInfo.bottomMargin = 0
printInfo.rightMargin = 0
let printOperation = NSPrintOperation(view: printView, printInfo: printInfo)
printOperation.run()
}
// 来自:如何打印 SwiftUI 视图
struct ContentView: View {
@State var someText = "Text here"
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text(someText)
TextField("A textfield", text: $someText)
Button("Print this View") {
startPrinting()
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
更改 rootView 允许打印 ContentView 中的某些元素。不是地球仪。不是在文本字段中输入的文本。它确实包括文本内容、文本字段提示和出现的打印预览窗格中的按钮文本。
@vadian 我能够添加一个按钮来打印地图视图,但到目前为止还没有注释。
Button("Print Map") {
let options = MKMapSnapshotter.Options()
options.region = centerRegion // defined above
options.size = CGSize(width: 600, height: 800)
let mapSnapshotter = MKMapSnapshotter(options: options)
mapSnapshotter.start { (snapshot, error) -> Void in
let imageView = NSImageView()
imageView.frame = NSRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 600, height: 800))
imageView.image = image
let info = NSPrintInfo.shared
info.horizontalPagination = .fit
info.verticalPagination = .fit
let operation = NSPrintOperation(view: imageView, printInfo: info)
operation.showsPrintPanel = true
operation.run()
}
}
}.buttonStyle(.borderedProminent)
// Under Signing and Capabilities > App Sandbox > Hardware > Printing checked