NSAttributedString multiple alignment

Hi everyone,


I would like to create programmatically a multiple alignment attributed string. I guess it can be done since I can make it in IB.

Basically, I need the first line to be left aligned and the second line to be right aligned.

Any help would be much appreciated. Thanks ;-)

Hi,


my solution:

override func viewDidLoad()
{
    super.viewDidLoad()

    let text = "Left alignment\nCenter alignment\nRight alignment"
    let rows = text.components(separatedBy: "\n")

    let attributedText = NSMutableAttributedString(string: text, attributes: [.foregroundColor: UIColor.white])
    attributedText.setAlignment(.left, for: rows[0])
    attributedText.setAlignment(.center, for: rows[1])
    attributedText.setAlignment(.right, for: rows[2])

    textView.attributedText = attributedText
}

extension NSMutableAttributedString
{
    func setAlignment(_ alignment: NSTextAlignment, for text: String)
    {
        if let range = string.range(of: text)
        {
            let style = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
            style.alignment = alignment

            addAttribute(.paragraphStyle, value: style, range: NSRange(range, in: string))
        }
    }
}
NSAttributedString multiple alignment
 
 
Q