user3690202
user3690202

Reputation: 4045

How to draw horizontally aligned NSAttributedString in Swift

I am trying to draw a multi-line string such that each line is horizontally aligned to the centre of the box. I am using NSAttributedString, thus:

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

Then later I draw the string using 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)

But it still comes out with each line aligned to the left. How can I draw a string in ios and center the alignment.

Upvotes: 1

Views: 2378

Answers (1)

ovo
ovo

Reputation: 2162

You may need to use draw(in rect: CGRect), rather than 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

Upvotes: 2

Related Questions