How to right-justify UILabel text?
thanks
myLabel.textAlignment = UITextAlignmentRight;
iOS Developer Library is a good resource.
it can be through interface builder. or label.textAlignment = UITextAlignmentRight;
You should set text alignment to justified and set attributed string base writing direction to 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
The above methods have been deprecated. The new method call is:
label.textAlignment = NSTextAlignmentRight;
you can using 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 simply set your text to your Label like This
self.YourLabel.setJustifiedRight("your texts")
Here is:
be careful if full justify needs to be applied, 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];