2017-08-31 81 views
0

我试图在我的swift应用程序中将自定义UIView保存为pdf,但是我失败了。无法通过swift创建PDF与UIView?

所以我尝试使用相同的方式与OC,它工作正常,但不与迅速。

这些是我的swift和OC测试代码,它们都可以在模拟器和设备中显示相同的块。

迅速:

@objc class TestViewController: UIViewController { 
    override func viewDidAppear(_ animated: Bool) { 
     super.viewDidAppear(animated) 
     let sub = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) 
     sub.backgroundColor = .red 
     view.addSubview(sub) 

     let data = NSMutableData() 
     UIGraphicsBeginPDFContextToData(data, view.bounds, nil) 
     UIGraphicsBeginPDFPage() 
     view.layer.draw(in: UIGraphicsGetCurrentContext()!) 
     UIGraphicsEndPDFContext() 

     let path = NSTemporaryDirectory() + "/pdftest_s.pdf" 
     data.write(toFile: path, atomically: true) 
     print(path) 
    } 
} 

OC:

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 
@end 

@implementation ViewController 
- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    UIView *sub = [UIView.alloc initWithFrame:CGRectMake(10, 10, 100, 100)]; 
    sub.backgroundColor = UIColor.redColor; 
    [self.view addSubview:sub]; 

    NSMutableData *data = [NSMutableData data]; 
    UIGraphicsBeginPDFContextToData(data, self.view.bounds, nil); 
    UIGraphicsBeginPDFPage(); 
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIGraphicsEndPDFContext(); 

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"pdftest.pdf"]; 
    [data writeToFile:path atomically:YES]; 
    NSLog(@"%@", path); 
} 
@end 

在这两种Xcode的8.3和9.0 beta6 OC工作正常,但不与迅速(3和4)。

我正在尝试使用UIPrintPageRenderer,它不工作!

+1

有differance view.layer.draw和self.view.layer渲染尝试修复它,然后再试 –

+0

它改变后呈现工作。谢谢。 –

回答

1

obj中的代码要渲染view.layer

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 

而在SWIFT代码,你忘了这样做

与渲染代替view.layer.draw(in: UIGraphicsGetCurrentContext()!)

希望这是有帮助的

0

您需要在您当前的图形上下文中呈现您的视图。在swift3你可以做到这一点作为

view.layer.render(in: UIGraphicsGetCurrentContext()!)

按照苹果文档

renderInContext:呈现层及其子层到 指定的上下文。