在objective-c中这个答案的帮助下,这是一个swift中的工作示例:
override func draw(_ rect: CGRect) {
super.draw(rect)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(red: 1.0,green: 1.0,blue: 1.0,alpha: 1.0)
context.fill(self.bounds)
let filepath = (Bundle.main.path(forResource: "Example", ofType: "pdf"))! as String
let url = URL(fileURLWithPath: filepath)
let pdf: CGPDFDocument! = CGPDFDocument(url as CFURL)
let page: CGPDFPage = pdf.page(at: 1)!
let pageRect: CGRect = page.getBoxRect(CGPDFBox.mediaBox)
let scale: CGFloat = min(self.bounds.size.width / pageRect.size.width , self.bounds.size.height / pageRect.size.height)
context.saveGState()
context.translateBy(x: 0.0, y: self.bounds.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.scaleBy(x: scale, y: scale)
context.drawPDFPage(page)
context.restoreGState()
}
上面的代码是drawRect
您将在其中显示 pdf 的视图的方法。只需将此视图作为子视图添加到您的 viewControllerviewDidLoad
方法中即可。