无法通过 swift 使用 UIView 创建 pdf? [英] Unable create pdf with UIView by swift?

查看:33
本文介绍了无法通过 swift 使用 UIView 创建 pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的 swift 应用程序中将自定义 UIView 保存为 pdf,但我失败了.

I tried to save custom UIView to pdf in my swift app, but I failed.

所以我尝试使用与 OC 相同的方式,它工作正常,但不适用于 swift.

So I try to use same way with OC, it is working fine, but not with swift.

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

These is my test code with swift and OC, both of them can display same block in simulator and device.

快速:

@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 中运行良好,但不适用于 swift(3 和 4).

In both Xcode 8.3 and 9.0 beta6 OC is working fine, but not with swift (3 and 4).

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

I was trying to use UIPrintPageRenderer, it is not working!

推荐答案

在 Obj 代码中你正在渲染 view.layer

In Obj code you are rendering view.layer

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

在快速代码中你忘记这样做

while in swift code you forgot to do so

用渲染替换view.layer.draw(in: UIGraphicsGetCurrentContext()!)

希望对你有帮助

这篇关于无法通过 swift 使用 UIView 创建 pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆