gpt4 book ai didi

ios - 无法通过 UIView 通过 swift 创建 pdf?

转载 作者:行者123 更新时间:2023-11-28 15:21:08 30 4
gpt4 key购买 nike

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

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

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

swift :

@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)
}
}

奥委会:

#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)中却不行。

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

最佳答案

在 Obj 代码中,您正在渲染 view.layer

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

在 swift 代码中你忘记这样做了

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

希望对你有帮助

关于ios - 无法通过 UIView 通过 swift 创建 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45980620/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com