How to align text UILabel?

How to align text UILabel?

thanks

+8
source share
6 answers
myLabel.textAlignment = UITextAlignmentRight; 

iOS Developer Library is a good resource.

+7
source

You must set the text alignment for alignment and set the writing direction of the base line in RightToLeft:

 var label: UILabel = ... var text: NSMutableAttributedString = ... var paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paragraphStyle.alignment = NSTextAlignment.Justified paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping paragraphStyle.baseWritingDirection = NSWritingDirection.RightToLeft text.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, text.length)) label.attributedText = text 
+6
source

The above methods are deprecated. New method call:

 label.textAlignment = NSTextAlignmentRight; 
+4
source

Here: be careful if you need to apply the full justification, firstLineIndent should not be zero.

 NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc] init]; paragraph.alignment = NSTextAlignmentJustified; paragraph.baseWritingDirection = NSWritingDirectionRightToLeft; paragraph.firstLineHeadIndent = 1.0; NSDictionary* attributes = @{ NSForegroundColorAttributeName: [UIColor colorWithRed:0.2 green:0.239 blue:0.451 alpha:1],NSParagraphStyleAttributeName: paragraph}; NSString* txt = @"your long text"; NSAttributedString* aString = [[NSAttributedString alloc] initWithString: txt attributes: attributes]; 
+2
source

it can be through the interface builder. or label.textAlignment = UITextAlignmentRight;

+1
source

You can use this extension below for Swift 5:

 extension UILabel { func setJustifiedRight(_ title : String?) { if let desc = title { let text: NSMutableAttributedString = NSMutableAttributedString(string: desc) let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.alignment = NSTextAlignment.justified paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping paragraphStyle.baseWritingDirection = NSWritingDirection.rightToLeft text.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, text.length)) self.attributedText = text } } } 

and just set your text on your label like this

 self.YourLabel.setJustifiedRight("your texts") 
0
source

All Articles