How to right-justify UILabel text?

前端 未结 6 1120
悲哀的现实
悲哀的现实 2021-02-14 12:38

How to right-justify UILabel text?

thanks

相关标签:
6条回答
  • 2021-02-14 12:54
    myLabel.textAlignment = UITextAlignmentRight;
    

    iOS Developer Library is a good resource.

    0 讨论(0)
  • 2021-02-14 12:57

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

    0 讨论(0)
  • 2021-02-14 12:59

    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
    
    0 讨论(0)
  • 2021-02-14 12:59

    The above methods have been deprecated. The new method call is:

    label.textAlignment = NSTextAlignmentRight;
    
    0 讨论(0)
  • 2021-02-14 13:05

    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")
    
    0 讨论(0)
  • 2021-02-14 13:10

    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];
    
    0 讨论(0)
提交回复
热议问题