ios - 如何对齐 Right-Justify UILabel?

标签 ios swift alignment uilabel

备注:

实现:

myLabel.textAlignment = .right

没有解决我的问题,这不是我要的。



我想要实现的是让标签的对齐方式右对齐

为了更清楚:

这就是对齐的样子:

enter image description here

这就是 justify 对齐的样子:

enter image description here

如果您没有看到两个屏幕截图之间有任何差异,您可以通过标签的右(尾随)约束识别它,您会在第二个屏幕截图中注意到标签的整个宽度已被填充文本。

如第二张截图所示,让label对齐会默认Left-Justify,即最后一行对齐left

如何让标签向右对齐?换句话说,我希望文本就像第二个屏幕截图一样,只是我希望最后一行向右移动。

如果您想知道这样做的目的是什么,它适合从右到左的语言。

最佳答案

感谢@user6788419提到 appropriate answer .

要实现它,您应该使用 NSMutableParagraphStyle :

An object that enables changing the values of the subattributes in a paragraph style attribute.

它使您能够同时进行 alignmentbaseWritingDirection,从而获得所需的输出:

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
    }
}

输出将是:

enter image description here

关于ios - 如何对齐 Right-Justify UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46462936/

相关文章:

ios - 关闭 UIScrollView 的滚动但保留缩放功能

ios - Swift 3 - 为每个设备设置 X-Y 轴 UILabel

html - 图像在 HTML 中对齐

flutter - 如何在 Flutter 中左对齐 OutlineButton 图标

html - 如何正确对齐文本?

ios - 当键盘出现并且相应的文本字段位于表格 View 部分标题中时,停止表格 View 的自动滚动

ios - 如何使 iOS 7 应用程序向后兼容?

ios - 表情符号支持 NSAttributedString 属性(字距调整/段落样式)

ios - 向 UITableViewCell 添加边距

ios - 像素大小的图标 - Swift 2.0