简体   繁体   中英

How to align Right-Justify UILabel?

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:

在此处输入图片说明

And that's how justify alignment looks:

在此处输入图片说明

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, ie 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.

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:

在此处输入图片说明

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM