我正在从我的Swift应用程序生成PDF发票。因为不是所有修补的地址都有相同的深度,所以我使用回车符来布局文本。例如,地址、日期、发票编号、主题行和叙述。这一切都工作得很好,但是,我想用粗体文本格式化主题行。我已经环顾了这个主题,却一无所获。本质上,我的问题是你可以嵌套NSAttributed字符串,这样我就可以用粗体格式设置主题行的格式,而不必创建另一个NSAttributed字符串,这将意味着我失去了布局规则?
这是我的代码
let textFont = UIFont.systemFont(ofSize: 10.0, weight: .regular)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .natural
paragraphStyle.lineBreakMode = .byWordWrapping
let textAttributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.kern : -0.15] as [NSAttributedString.Key : Any]
let attributedText = NSAttributedString(string: "\(billAddress)\r\r\r\("Invoice number: \ .
(invoiceNumber)")\r\("Date: \(mydate)")\r\r\r\("To")\r\r\(subjectline)\r\r\(narrative)",
attributes:
textAttributes as [NSAttributedString.Key : Any])欢迎任何帮助/想法/解决方案
发布于 2020-03-26 01:20:35
您可以使用NSMutableAttributedString,并使用.append(_:)方法追加字符串的不同部分。(https://developer.apple.com/documentation/foundation/nsmutableattributedstring/1417879-append)
发布于 2020-03-27 03:44:32
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .natural
paragraphStyle.lineBreakMode = .byWordWrapping
let defaultAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0, weight: .regular),
NSAttributedString.Key.kern : -0.15]
let boldAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0, weight: .bold),
NSAttributedString.Key.kern : -0.15]
let attributedText = NSMutableAttributedString()
attributedText.append(NSAttributedString(string: (billAddress), attributes: defaultAttributes))
attributedText.append(NSAttributedString(string: "\r\r"))
attributedText.append(NSAttributedString(string: "Invoice number: \(invoiceNumber)", attributes: defaultAttributes))
attributedText.append(NSAttributedString(string: "\r"))
attributedText.append(NSAttributedString(string: "Date: \(mydate)", attributes: defaultAttributes))
attributedText.append(NSAttributedString(string: "\r\r"))
attributedText.append(NSAttributedString(string: "To", attributes: defaultAttributes))
attributedText.append(NSAttributedString(string: "\r\r"))
attributedText.append(NSAttributedString(string: subjectline, attributes: boldAttributes))
attributedText.append(NSAttributedString(string: "\r"))
attributedText.append(NSAttributedString(string: narrative, attributes: defaultAttributes))
let textRect = CGRect(x: 40, y: textTop, width: pageRect.width - 240,
height: pageRect.height - textTop - pageRect.height / 2 )
attributedText.draw(in: textRect)https://stackoverflow.com/questions/60852112
复制相似问题