设备方向更改时调整PDF查看大小

时间:2019-01-11 15:14:40

标签: ios iphone swift pdfkit

我的应用程序中有一个ViewController,允许用户打开PDF。该应用程序支持设备的横向和纵向方向。当用户在打开PDF后更改设备方向时出现问题。 PDF有两页: 第1页-所有粉红色和 第2页-全部为紫色

打开PDF并用户更改设备方向后,我遇到了框架问题。如果以纵向打开PDF,则当设备的顺序更改为横向时,pdf只会填满屏幕的一半: Portrait Orientation after being opened in a portrait orientation Landscape Orientation after being opened in portrait orientation

同样,如果以横向打开PDF,则仅当设备的方向为纵向时pdf才会显示在屏幕的一半: Lanscape Orientation after being opened in a landscape Orientation Portrait Orientation after being opened in a landscape Orientation

这是我的代码:

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)可以解决我的问题,但是我发现没有变化。

1 个答案:

答案 0 :(得分:1)

最好的方法是将布局约束添加到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方法中删除代码。