如何在Swift中以编程方式调整UILabel行间距?

问题描述:

我有一条多行 UILabel ,如下所示:

I have a multiline UILabel as shown here:

我使用以下代码实现了这个目的:

I achieved this using the following code:

label.lineBreakMode = .ByWordWrapping
label.numberOfLines = 2

我试图减少 第一行和第二行之间的行间距,我尝试使用以下代码:

I'm trying to "decrease" the line spacing between the 1st line and 2nd line, and I tried to use the following code:

let text = label.attributedText
let mas = NSMutableAttributedString(attributedString:text!)
            mas.replaceCharactersInRange(NSMakeRange(0, mas.string.utf16.count),
                withString: label.text!)
label.attributedText = mas

然而,它似乎不起作用。

However, it does not seem to work.

谢谢

你在右边的tra ck与NSAttributedString。您需要设置段落样式的行间距:

You're on the right track with NSAttributedString. You need to set the line spacing of the paragraph style:

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 30 // Whatever line spacing you want in points
    attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
    label.attributedText = attributedString;