2

Remark:

Implementing:

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 left alignment looks:

enter image description here

And that's how justify 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 left.

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.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143

2 Answers2

12

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() {
        super.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(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, text.length))

        lblDescription.attributedText = text
    }
}

The output would be:

enter image description here

Hasya
  • 9,792
  • 4
  • 31
  • 46
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
0

There is not ENUM available for right justified!

You have to choose from NSTextAlignmentLeft,NSTextAlignmentRight,NSTextAlignmentCenter,NSTextAlignmentJustified,NSTextAlignmentNatural.

You have added screenshot of xcode's interface builder! once check it in simulator or device.

If you want space at left or right side in label with justified text then you can play with edge insets.

For example Left padding in label.

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75