备注:
实现:
myLabel.textAlignment = .right
没有解决我的问题,这不是我要的。
我想要实现的是让标签的对齐方式右对齐。
为了更清楚:
这就是左
对齐的样子:
这就是 justify
对齐的样子:
如果您没有看到两个屏幕截图之间有任何差异,您可以通过标签的右(尾随)约束识别它,您会在第二个屏幕截图中注意到标签的整个宽度已被填充文本。
如第二张截图所示,让label对齐会默认Left-Justify,即最后一行对齐left
。
如何让标签向右对齐?换句话说,我希望文本就像第二个屏幕截图一样,只是我希望最后一行向右移动。
如果您想知道这样做的目的是什么,它适合从右到左的语言。
最佳答案
感谢@user6788419提到 appropriate answer .
要实现它,您应该使用 NSMutableParagraphStyle :
An object that enables changing the values of the subattributes in a paragraph style attribute.
它使您能够同时进行 alignment
和 baseWritingDirection
,从而获得所需的输出:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lblDescription: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let text: NSMutableAttributedString = NSMutableAttributedString(string: "In vertebrates, it is composed of blood cells suspended in blood plasma. Plasma, which constitutes 55% of blood fluid, is mostly water (92% by volume), and contains dissipated proteins...")
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .justified
paragraphStyle.baseWritingDirection = .rightToLeft
paragraphStyle.lineBreakMode = .byWordWrapping
text.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, text.length))
lblDescription.attributedText = text
}
}
输出将是:
关于ios - 如何对齐 Right-Justify UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46462936/