NSAttributedString: aligning substrings

I have a label at the top of a view. I want the label to display a left-aligned string, a centre-aligned string, and a right-alinged string: something like this:


  |Left              Centre           Right|


I tried to do this using an attributed string and paragraph styles. I defined left, right, and centre-aligment paragraph styles, then assigned them to the relevant ranges of the attributed string “LeftCentreRight”. Here’s the code I used (from a playground):


let testLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 600.0, height: 22.0))
testLabel.backgroundColor = UIColor.blue
let leftStyle = NSMutableParagraphStyle()
leftStyle.alignment = .left
let centreStyle = NSMutableParagraphStyle()
centreStyle.alignment = .center
let rightStyle = NSMutableParagraphStyle()
rightStyle.alignment = .right
let attributes: [NSAttributedString.Key: Any] = [
  .foregroundColor: UIColor.white
let titleString = NSMutableAttributedString(string: "LeftCentreRight", attributes: attributes)
titleString.addAttribute(.paragraphStyle, value: leftStyle, range: NSRange(location: 0, length: 4))
titleString.addAttribute(.paragraphStyle, value: centreStyle, range: NSRange(location: 4, length: 6))
titleString.addAttribute(.paragraphStyle, value: rightStyle, range: NSRange(location: 10, length: 5))
testLabel.attributedText = titleString


And this is what I got:


|LeftCentreRight                         |


I tried concatenating three separate attributed strings, with the three paragraph styles applied to each. But I got the same result, except that “LeftCentreRight” was centred.


Could someone suggest a good way to do this?

Powered by WPeMatico

You may also like...

Comments are closed.