如何在 Swift 中绘制水平对齐的 NSAttributedString

How to draw horizontally aligned NSAttributedString in Swift

我正在尝试绘制多行字符串,使每行都与框的中心水平对齐。我正在使用 NSAttributedString,因此:

let paraStyle = NSMutableParagraphStyle()
paraStyle.alignment = .center
textAttrs = [
    NSFontAttributeName: font!,
    NSForegroundColorAttributeName: UIColor.white,
    NSParagraphStyleAttributeName: paraStyle,
    NSBaselineOffsetAttributeName: NSNumber(floatLiteral: 0.0)
]

然后我使用 NSAttributedString draw()

绘制字符串
let uiText = NSAttributedString(string: text, attributes: textAttrs)
let point = CGPoint(x: self.bounds.width / 2 - uiText.size().width / 2, y: self.bounds.height / 2 - uiText.size().height / 2)
uiText.draw(at: point)

但它仍然是每行都左对齐。如何在 ios 中绘制字符串并居中对齐。

您可能需要使用 draw(in rect: CGRect),而不是 draw(at point: CGPoint)

override func draw(_ rect: CGRect) {

    let paraStyle = NSMutableParagraphStyle()
    paraStyle.alignment = .center

    let textAttrs = [
        NSFontAttributeName: UIFont.systemFont(ofSize: 17),
        NSForegroundColorAttributeName: UIColor.blue,
        NSParagraphStyleAttributeName: paraStyle,
        NSBaselineOffsetAttributeName: NSNumber(floatLiteral: 0.0)
    ]

    let text = "The American student who was released last week after being held in captivity for more than 15 months in North Korea has died, his family says. Otto Warmbier, 22, returned to the US last Tuesday, but it emerged he had been in a coma for a year.North Korea said botulism led to the coma, but a team of US doctors who assessed him dispute this account.Mr Warmbier was sentenced to 15 years of hard labour for attempting to steal a propaganda sign from a hotel."

    let uiText = NSAttributedString(string: text, attributes: textAttrs)
    uiText.draw(in: rect)

    layer.borderColor = UIColor.black.cgColor
    layer.borderWidth = 2
}