Swift 4 - NSGraphicsContext.setCurrent() 没有成员 'setCurrent'

Swift 4 - NSGraphicsContext.setCurrent() has no member 'setCurrent'

所以我尝试使用与 .

类似的方法将文本叠加到 PDF 文档上

我使用一个函数来设置当前的图形上下文,就像它在文档中所说的那样。

let pdfPage: CGPDFPage = pdf.page(at: 1)!
            //var pageRect = pdfPage.getBoxRect(CGPDFBox.mediaBox)
            //print(pageRect)

            let doc: PDFDocument = PDFDocument(url: pdfURL!)!
            let page: PDFPage = doc.page(at: 0)!
            var mediaBox: CGRect = page.bounds(for: .mediaBox)

            let context = CGContext(destinationURL as CFURL, mediaBox: &mediaBox, nil)
            let graphicsContext = NSGraphicsContext(cgContext: context!, flipped: false)
            NSGraphicsContext.setCurrent(graphicsContext)

            context!.beginPDFPage(nil)

            page.draw(with: .mediaBox, to: context!)

            let style = NSMutableParagraphStyle()
            style.alignment = .center

            let richText = NSAttributedString(string: "Hello, world!", attributes: [
                NSAttributedStringKey.font: NSFont.systemFont(ofSize: 64),
                NSAttributedStringKey.foregroundColor: NSColor.red,
                NSAttributedStringKey.paragraphStyle: style
                ])

            let richTextBounds = richText.size()
            let point = CGPoint(x: mediaBox.midX - richTextBounds.width / 2, y: mediaBox.midY - richTextBounds.height / 2)

            context!.saveGState()
            do {
                context!.translateBy(x: point.x, y: point.y)
                context!.rotate(by: .pi / 5)
                richText.draw(at: .zero)
            }
            context!.restoreGState()



            context!.endPDFPage()
            NSGraphicsContext.setCurrent(nil)
            context?.closePDF()
        }

行:

NSGraphicsContext.setCurrent(graphicsContext)

抛出一个错误 "Type 'NSGraphicsContext' has no member 'setCurrent'"

有人知道发生了什么事吗?就框架而言,我缺少什么吗?

您需要使用 current class 属性.

NSGraphicsContext.current = graphicsContext