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

时间:2017-06-20 01:27:55

标签: ios swift nsattributedstring

我正在尝试绘制一个多行字符串,使每行与水平中心对齐。我正在使用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中绘制字符串并使对齐居中。

1 个答案:

答案 0 :(得分:0)

您可能需要使用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
}

smaple