【发布时间】:2011-10-13 01:58:22
【问题描述】:
如何右对齐 UILabel 文本?
谢谢
【问题讨论】:
如何右对齐 UILabel 文本?
谢谢
【问题讨论】:
新的方法调用是:
label.textAlignment = NSTextAlignmentRight;
【讨论】:
您可以在下面为 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")
【讨论】:
这里是:
如果需要应用完全对齐,请小心,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];
【讨论】:
您应该将文本对齐设置为两端对齐,并将属性字符串基本书写方向设置为 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
【讨论】:
可以通过界面生成器。 或 label.textAlignment = UITextAlignmentRight;
【讨论】:
myLabel.textAlignment = UITextAlignmentRight;
iOS Developer Library 是一个很好的资源。
【讨论】:
UITextAlignmentRight 或 NSTextAlignmentRight 仅右对齐文本,但文本不对齐请参阅 @Hashem Aboonajmi 或 @Aryan 答案