[英]Resize PDF View when device orientation changes
我的應用程序中有一個ViewController,它允許用戶打開PDF。 該應用程序支持設備的橫向和縱向方向。 當用戶在打開PDF后更改設備方向時出現問題。 PDF有兩頁:第1頁-全粉紅色,第2頁-全紫
打開PDF並且用戶更改設備方向后,我遇到了框架問題。 如果以縱向打開PDF,則當設備的順序更改為橫向時,pdf只會填滿屏幕的一半:
同樣,如果以橫向打開PDF,則僅當設備的方向為縱向時pdf才會顯示在屏幕的一半:
這是我的代碼:
import UIKit
import PDFKit
class PDFfun: UIViewController {
var pdfView = PDFView()
override func viewDidLoad() {
super.viewDidLoad()
pdfView = PDFView(frame: self.view.frame)
if let documentURL = Bundle.main.url(forResource: "Blank", withExtension: "pdf"),
let document = PDFDocument(url: documentURL),
let _ = document.page(at: 0) {
pdfView.document = document
pdfView.autoScales = true
pdfView.backgroundColor = UIColor.lightGray
pdfView.autoScales = true
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("landscape")
pdfView = PDFView(frame: view.frame)
pdfView.autoScales = true
} else {
print("portait")
pdfView = PDFView(frame: view.frame)
pdfView.autoScales = true
}
}
}
我累了添加override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
修復了我的問題,但是我沒有發現任何變化。
最好的方法是將布局約束添加到pdfView中。 例如,在您的viewDidLoad中:
pdfView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pdfView)
view.addConstraints([
NSLayoutConstraint(item: pdfView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pdfView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pdfView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pdfView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
])
如果您不想使用layoutConstraint,也可以在viewDidLayoutSubviews方法中為pdfView設置框架:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pdfView.frame = view.frame
}
並且不要忘記在viewWillTransition方法中刪除您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.