web-dev-qa-db-fra.com

Comment ajouter un espacement aux lignes dans NSAttributedString

Je crée une application qui formate les scénarios, j'utilise un NSAttributedString pour formater le texte entré dans un UITextView, mais certaines lignes sont trop rapprochées.

Je me demandais si quelqu'un pourrait fournir un exemple de code ou une astuce sur la façon de modifier la marge entre ces lignes afin qu'il y ait plus d'espace entre elles.

Ci-dessous est une image d'un autre programme de scénarisation de bureau qui montre ce que je veux dire, remarquez comment il y a un peu d'espace avant chaque bit où il est écrit "DOROTHY".

enter image description here

21
James Campbell

L'exemple de code suivant utilise le style de paragraphe pour ajuster l'espacement entre les paragraphes d'un texte.

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];

Pour ajuster sélectivement l'espacement de certains paragraphes, appliquez le style de paragraphe uniquement à ces paragraphes.

J'espère que cela t'aides.

49
Joe Smith

Grande réponse @Joe Smith

Au cas où quelqu'un voudrait voir à quoi cela ressemble dans 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
18
Nathaniel

Voici la version 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
5
enigma