我正在使用 iOS PDFKit 编写 pdf。通常,我可以通过执行以下操作来获取单个文本项(例如标题)的高度:
return titleStringRect.origin.y + titleStringRect.size.height
其中 titleStringRect 是包含字符串的 CGRect。返回的值是该文本底部的 y 坐标,以便我知道从哪里开始编写下一行文本。我还没有找到知道段落结束位置的方法。我发现的解决方案是只制作一个足够大的 CGRect ,该段落肯定适合。我需要根据将写入其中的字符串确切地知道 CGRect 的高度应该是多少。这是我的代码:
func addParagraph(pageRect: CGRect, textTop: CGFloat, text: String) {
let textFont = UIFont(name: "Helvetica", size: 12)
let backupFont = UIFont.systemFont(ofSize: 12, weight: .regular)
// Set paragraph information. (wraps at word breaks)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .natural
paragraphStyle.lineBreakMode = .byWordWrapping
// Set the text attributes
let textAttributes = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: textFont ?? backupFont
]
let attributedText = NSAttributedString(
string: text,
attributes: textAttributes
)
let textRect = CGRect(
x: 50.0,
y: textTop,
width: pageRect.width - 100,
height: pageRect.height - textTop - pageRect.height / 5.0
)
attributedText.draw(in: textRect)
}
正如你所看到的,上面的代码只是创建了一个 CGRect,它是前一个文本下方空间的 1/5,而不管段落实际有多少行。我已经尝试平均每行的字符数,以估计该段落将有多少行,但这是不可靠的,绝对是一个 hack。我需要的是 addParagraph 函数返回段落底部的 y 坐标,以便我知道从哪里开始编写下一段内容。