Nstextalignment.Justified for Uilabel Does Not Work

NSTextAlignment.Justified for UILabel does not work

You have to create an NSMutableParagraphStyle in combination with an NSAttributedString in order to display text as justified.
The important part is to set NSBaselineOffsetAttributedName to 0.0.

Here's an example how to put everything together:

let sampleText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Justified

let attributedString = NSAttributedString(string: sampleText,
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSBaselineOffsetAttributeName: NSNumber(float: 0)
])

let label = UILabel()
label.attributedText = attributedString
label.numberOfLines = 0
label.frame = CGRectMake(0, 0, 400, 400)


let view = UIView()
view.frame = CGRectMake(0, 0, 400, 400)
view.addSubview(label)

Credits for NSBaselineOffsetAttributedName: https://stackoverflow.com/a/19445666/2494219

IOS: Justify text in UILabel not working in UI

It seems like a bug of UILabel,but you can fix it with a tiny change in your storyboard.

Click the more button in the same line of NSTextAlignments,add a little Head Indent ,such as 0.1 .

Sample Image

Your UILabel will work just fine.

Sample Image

How to right-justify UILabel text?


myLabel.textAlignment = UITextAlignmentRight;

iOS Developer Library is a good resource.

Center justify UILabel text?

I found the answer there : https://stackoverflow.com/a/27548566/833816

It works by adding paragraphStyle.firstLineHeadIndent = 0.001

Full sample:

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Justified
paragraphStyle.firstLineHeadIndent = 0.001

let mutableAttrStr = NSMutableAttributedString(attributedString: detailsLabel.attributedText)
mutableAttrStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, mutableAttrStr.length))
myLabel.attributedText = mutableAttrStr

NSTextAlignmentCenter for UILabel not working

I guess the problem is coming from :

[((MyView *)self.customView).myLabel sizeToFit];

Centering does not change the frame.origin.x of your label.
But if you apply sizeToFit afterwards, all content will be centered in a smaller zone (without changing the x offset) and will get the feeling that it's not centered anymore.



Related Topics



Leave a reply



Submit