iOSでPDFを表示する方法を知らなかったのでメモ書き
//: Playground - noun: a place where people can play
import PlaygroundSupport
import UIKit
import CoreGraphics
class PDFView: UIView {
var page: CGPDFPage?
override func draw(_ rect: CGRect) {
guard let page = page else { return }
guard let context = UIGraphicsGetCurrentContext() else {
fatalError()
}
context.translateBy(x: 0, y: rect.size.height)
context.scaleBy(x: 1.0, y: -1.0)
let box = page.getBoxRect(.mediaBox)
let xScale = rect.size.width / box.size.width
let yScale = rect.size.height / box.size.height
let scale = min(xScale, yScale)
let tx = (rect.size.width - box.size.width * scale) / 2
let ty = (rect.size.height - box.size.height * scale) / 2
context.translateBy(x: tx, y: ty)
context.scaleBy(x: scale, y: scale)
context.drawPDFPage(page)
}
}
guard let url = NSURL(string: "http://devstreaming.apple.com/videos/wwdc/2016/402h429l9d0hy98c9m6/402/402_whats_new_in_swift.pdf"), let doc = CGPDFDocument(url) else {
fatalError()
}
let pageCount = doc.numberOfPages
let number = 1
let page = doc.page(at: number)
let view = PDFView(frame: UIScreen.main.bounds)
view.backgroundColor = UIColor.lightGray
view.page = page
PlaygroundPage.current.liveView = view
上のコードはPlaygroundで検証しました。PlaygroundPage.current.liveView = view
でPlaygroundでもViewの検証ができます。
今回はシングルページの表示ですが、doc.page(at: number)
でページを切り替えれるので、簡単にPDFViewerみたいなアプリも作れそうですね