如何在NSAttributedString中为行添加间距

Jam*_*ell 21 nsattributedstring ios

我正在制作一个格式化剧本的应用程序,我使用NSAttributedString来格式化输入到UITextView中的文本,但是有些行太靠近了.

我想知道是否有人可以提供代码示例或如何改变这些行之间的边距的提示,以便它们之间有更多的空间.

下面是另一个桌面编剧程序的图像,它演示了我的意思,注意每个位之前有一点空间,它说的是"DOROTHY".

在此输入图像描述

Joe*_*ith 49

以下示例代码使用段落样式来调整文本段落之间的间距.

UIFont *font = [UIFont fontWithName:fontName size:fontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight;
NSDictionary *attributes = @{NSFontAttributeName:font,
                             NSForegroundColorAttributeName:[UIColor whiteColor],
                             NSBackgroundColorAttributeName:[UIColor clearColor],
                             NSParagraphStyleAttributeName:paragraphStyle,
                            };
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
Run Code Online (Sandbox Code Playgroud)

要有选择地调整某些段落的间距,请将段落样式仅应用于这些段落.

希望这可以帮助.


Nat*_*iel 18

很棒的答案@Joe Smith

万一有人想看看Swift 2中的内容.*:

    let font = UIFont(name: String, size: CGFloat)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight
    let attributes = [NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle]

    let attributedText = NSAttributedString(string: String, attributes: attributes)
    self.textView.attributedText = attributedText
Run Code Online (Sandbox Code Playgroud)


eni*_*gma 5

这是Swift 4. *版本:

let string =
    """
    A multiline
    string here
    """
let font = UIFont(name: "Avenir-Roman", size: 17.0)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 0.25 * (font?.lineHeight)!

let attributes = [NSAttributedStringKey.font: font as Any, NSAttributedStringKey.paragraphStyle: paragraphStyle]

let attrText = NSAttributedString(string: string, attributes: attributes)
self.textView.attributedText = attrText
Run Code Online (Sandbox Code Playgroud)