如何正确对齐UILabel文本?

时间:2011-07-26 03:13:58

标签: objective-c cocoa-touch

如何对UILabel文本进行右对齐?

感谢

6 个答案:

答案 0 :(得分:7)

myLabel.textAlignment = UITextAlignmentRight;

iOS Developer Library是一个很好的资源。

答案 1 :(得分:5)

您应该将文本对齐设置为对齐并将属性字符串基本书写方向设置为RightToLeft:

# chmod -R 777 /opt/apache-tomcat-8.0.23

答案 2 :(得分:4)

上述方法已被弃用。新方法调用是:

label.textAlignment = NSTextAlignmentRight;

答案 3 :(得分:2)

这是: 如果需要应用完全证明,请注意firstLineIndent不应为零。

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];

答案 4 :(得分:1)

它可以通过界面构建​​器。 或 label.textAlignment = UITextAlignmentRight;

答案 5 :(得分:1)

您可以将以下扩展程序用于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
       }
    }
}

并像这样简单地将文本设置为标签

self.YourLabel.setJustifiedRight("your texts")