NSAttributedString

 NSAttributedString 是一个特殊的类,可以用来操作富文本.继承自NSObject

NSAttributedString 里面包含一个类似NSString,同事还存储了有关文本格式的信息,比如字体.颜色等。从IOS6出现之后正式登上台面。


NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor greenColor]};

    NSAttributedString *aString = [[NSAttributedString alloc] initWithString:@"Green message!" attributes:attributes];


把字典换成 

 NSDictionary *attributes = @{NSForegroundColorAttributeName:[UIColor greenColor],NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle]};

下面是一些常见的属性



NSAttributedString 转换成 PDF 格式可以通过以下步骤实现: 1. 创建一个 NSMutableData 对象来存储 PDF 数据。 2. 创建一个 UIGraphicsPDFRenderer 对象,指定页面大小和页面边距。 3. 在 renderer 上调用 drawPDFPage 方法,将 NSAttributedString 绘制到 PDF 页面上。 4. 关闭 renderer,将 PDF 数据写入 NSMutableData 对象中。 以下是示例代码: ```swift let pdfData = NSMutableData() let pageSize = CGSize(width: 8.5 * 72, height: 11 * 72) let pageRect = CGRect(origin: .zero, size: pageSize) let renderer = UIGraphicsPDFRenderer(bounds: pageRect) let attributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: UIColor.black ] let attributedString = NSAttributedString(string: "Hello, World!", attributes: attributes) let pdfMetaData = [ kCGPDFContextCreator: "My App", kCGPDFContextAuthor: "Me" ] let pdfFormat = UIGraphicsPDFRendererFormat() pdfFormat.documentInfo = pdfMetaData as [String: Any] renderer.writePDF(to: pdfData) { context in context.beginPage() attributedString.draw(in: pageRect) } // Save PDF data to file or display in a UIWebView ``` 在上面的示例中,我们创建了一个 NSMutableData 对象来存储 PDF 数据。然后,我们创建了一个 UIGraphicsPDFRenderer 对象,并指定了页面大小和边距。接下来,我们定义了一个 NSAttributedString,并使用指定的字体和颜色。 在 renderer 上调用 beginPage 方法,开始一个新的 PDF 页面。然后,我们调用 draw 方法,并将 NSAttributedString 绘制到页面上。最后,我们关闭 renderer 并将 PDF 数据写入 NSMutableData 对象中。你可以将 PDF 数据保存到文件或在 UIWebView 中显示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值