Ahmad F Ahmad F - 3 years ago 264
Swift Question

How to align Right-Justify UILabel?



myLabel.textAlignment = .right

does not solves my problem, that is not what I am asking for.

What I am trying to achieve is to let the alignment for the label to be Right-Justify.

To make it more clear:

That's how
alignment looks:

enter image description here

And that's how
alignment looks:

enter image description here

if you are not seeing any difference between the tow screenshots, you could recognize it by the right (trailing) constraint of the label, you will notice in the second screenshot the whole width of the label has been filled by the text.

As shown in the second screenshot, letting the label to be justified will make it Left-Justify by default, i.e the last line alignment is

How can I make let the label to be justified to the right? In other words, I want the text to be just like the 2nd screenshot except that I want the last short line to be shifted to the right.

If you wondering what is the purpose of doing such a thing, it would be appropriate for right to left languages.

Answer Source

Thanks to @user6788419 for mentioning the appropriate answer.

For achieving it, you should work with NSMutableParagraphStyle:

An object that enables changing the values of the subattributes in a paragraph style attribute.

It gives you the ability to the alignment and baseWritingDirection simultaneously, which leads to the desired output:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var lblDescription: UILabel!

    override func viewDidLoad() {

        let text: NSMutableAttributedString = NSMutableAttributedString(string: "In vertebrates, it is composed of blood cells suspended in blood plasma. Plasma, which constitutes 55% of blood fluid, is mostly water (92% by volume), and contains dissipated proteins...")

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .justified
        paragraphStyle.baseWritingDirection = .rightToLeft
        paragraphStyle.lineBreakMode = .byWordWrapping

        text.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, text.length))

        lblDescription.attributedText = text

The output would be:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download