我有同样的问题。我相信这是由 AppKit 用来有效显示 NSTableViews 的方法引起的。这似乎通过只为大约 3 个视图“页面”生成显示数据来优化,即减少大型 NSTableViews 的内存负载。要打印整个 NSTableView,请在打印var usesStaticContents: Bool { get set }
前将 NSTableView 实例属性设置为 true(打印完成后将其值返回为 false)。我已经在一张 33 x A4 横向页面的表格上成功地测试了它,它工作正常(尽管在显示打印面板之前需要大约 5 秒)。
这是对我有用的代码:
struct ReportsDetailView: View {
@Binding var reportNodes: [ReportNode]
@State private var viewToPrint = NSView()
@State private var printing = false
var body: some View {
VStack {
ReportsDetailTableVC(reportNodes: $reportNodes, viewToPrint: $viewToPrint, printing: $printing)
HStack {
Spacer()
Button("Print Report") {
printing = true
let scale: CGFloat = 800/viewToPrint.frame.width
let printInfo = NSPrintInfo()
printInfo.horizontalPagination = .automatic
printInfo.verticalPagination = .automatic
printInfo.isVerticallyCentered = true
printInfo.isHorizontallyCentered = true
printInfo.printer = NSPrinter(name: NSPrinter.printerNames[0])!
printInfo.paperSize = NSSize(width: 595.28, height: 841.89)
printInfo.topMargin = 10
printInfo.bottomMargin = 10
printInfo.leftMargin = 10
printInfo.rightMargin = 10
printInfo.orientation = .landscape
printInfo.scalingFactor = scale
let printOperation = NSPrintOperation(view: viewToPrint, printInfo: printInfo)
printOperation.run()
printing = false
}
.disabled(printing)
}
.padding(10)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ReportsDetailTableVC: NSViewControllerRepresentable {
@Environment(\.colorScheme) var colorScheme
@Binding var reportNodes: [ReportNode]
@Binding var viewToPrint: NSView
@Binding var printing: Bool
func makeNSViewController(context: Context) -> some NSViewController {
let reportsDetailVC = ReportsDetailTableViewController()
return reportsDetailVC
}
func updateNSViewController(_ nsViewController: NSViewControllerType, context: Context) {
guard let reportsDetailVC = nsViewController as? ReportsDetailTableViewController else {return}
reportsDetailVC.setContents(reportNodes: reportNodes)
if printing {
reportsDetailVC.tableView.scrollRowToVisible(0)
reportsDetailVC.tableView.usesStaticContents = true
reportsDetailVC.tableView.appearance = NSAppearance(named: .aqua)
reportsDetailVC.tableView.usesAlternatingRowBackgroundColors = false
}
else {
reportsDetailVC.tableView.usesStaticContents = false
reportsDetailVC.tableView.appearance = colorScheme == .light ? NSAppearance(named: .aqua) : NSAppearance(named: .darkAqua)
reportsDetailVC.tableView.usesAlternatingRowBackgroundColors = true
}
DispatchQueue.main.async {viewToPrint = reportsDetailVC.tableView}
}
}