我有一个显示 PDFView 的 iPad 应用程序。该应用程序可旋转到任何方向。PDFView 是全屏和单页的。以任一方向启动时,PDF 均按预期显示;整个第一页都是可见的,缩放以适应屏幕,而没有任何 PDF 出现在屏幕外。PDF 将始终是美国信纸大小的文档。
旋转时,PDF 会旋转,但不会调整大小。当将横向旋转为纵向时,PDF 显示“太小” - 外部有一个巨大的空白边框。当从纵向旋转到横向时,显示 PDF 的顶部三分之二,底部三分之一丢失在屏幕底部下方。
自动布局是在代码中配置的,并且相当直接(顶部、前导、高度和宽度)。
我查看了 Reveal 中的布局。它表明 PDFView 实际上正在按照 AutoLayout 配置正确调整大小。PDFView 内部是一个(私有)PDFDocumentView,它不会调整大小。
我发现“调整”视图的唯一方法是在 viewWillTransitionToSize 中捕捉旋转,从超级视图中删除 PDFView,并在将视图放回屏幕之前完全重新配置视图(包括重新加载文档)。这是一种糟糕的用户体验。
我将代码提取到一个简单的单视图产品中。整个 UIViewController 的代码如下。下面还有来自 Reveal 的屏幕截图,显示了该问题。在这种情况下,我以纵向启动应用程序,旋转设备,然后截取这些屏幕截图。(显示的 PDF 是 IRS 税表;我和应用程序都与 IRS 无关 - 它恰好是我使用的默认示例 PDF。)
#import "ViewController.h"
@import PDFKit;
@interface ViewController ()
@property (nonatomic, strong) PDFView *pdfView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupPDF];
}
-(void)setupPDF {
NSString *filename = @"myfile.pdf";
NSString *filenameWithoutPDF = [filename stringByReplacingOccurrencesOfString:@".pdf" withString:@""];
NSURL *url = [[NSBundle mainBundle] URLForResource:filenameWithoutPDF withExtension:@"pdf"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.pdfView = [[PDFView alloc] init];
PDFDocument *document = [[PDFDocument alloc] initWithData:data];
self.pdfView.document = document;
self.pdfView.displayMode = kPDFDisplaySinglePage;
self.pdfView.autoScales = YES;
[self.view addSubview:self.pdfView];
[self setupConstraints];
}
-(void)setupConstraints {
[self.pdfView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pdfView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pdfView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pdfView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pdfView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0]];
}
@end