NSAttributedString绘图-多少行?

问题描述 投票:1回答:1

我正在使用这种方法在PDF中绘制文本:

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        paragraphStyle.lineBreakMode = .byWordWrapping

        let textAttributes = [
            NSAttributedString.Key.paragraphStyle: paragraphStyle,
            NSAttributedString.Key.font: UIFont(name: "MySpecialFont", size: 16)!,
            NSAttributedString.Key.foregroundColor: UIColor.black
        ]

        let attributedText = NSAttributedString(
            string: myTextArray.first,
            attributes: textAttributes
        )

        let textRect = CGRect(
            x: 400,
            y: 40,
            width: 80,
            height: 40
        )

        attributedText.draw(in: textRect)

上面画出的文字很好。但是,有时,传递给它的字符串似乎太长,并且连续3行而不是2行。在这些情况下,我想使textRect更高。基本上知道要花费多少行,以便可以调整textRect

NSAttributedString中有几个函数可以给出字符串的长度,但是如果是单行,那就是长度。

是否有办法知道最终的attributedText将在textRect中占据几行?

ios swift string xcode nsattributedstring
1个回答
1
投票

使用NSAttributedString.boundingRect(with:options:context:)计算所需的大小。您应该将.usesLineFragmentOrigin作为选项传递,以便针对多行进行计算。通过所需的宽度;高度并不重要,因为它将扩展高度以包含完整的字符串,您可以使用它来计算出最终的矩形。

也就是说,根据您的描述,听起来您可以使高度非常大(通常值为10,000;但是也许您只想给三行空间)。由于您只是在这里画图;可用的矩形是否比要求的高无关紧要。只有更短才重要。

© www.soinside.com 2019 - 2024. All rights reserved.