【问题标题】:NSAttributedString Drawing - How Many Lines?NSAttributedString 绘图 - 多少行?
【发布时间】:2019-12-31 01:54:53
【问题描述】:

我正在使用这种方法在 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】:

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

    也就是说,根据您的描述,听起来您可以将高度设置得非常大(10,000 是通常的值;但也许您只想为三行留出空间)。因为你只是在这里画画;可用的矩形是否高于要求并不重要。仅当它更短时才重要。

    【讨论】:

    • 这些是表中列的标题。所以它们只需要垂直底部对齐。
    • 感觉带有numberOfLines = 3sizeThatFits() 的UILabel 将是一个很有前途的工具,而不是自定义绘图。它包括可能有用的附加功能,例如字体收紧 (allowsDefaultTighteningForTruncation)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多