AttributedString

Bonjour,


 


J'aimerais savoir s'il est possible d'utiliser une attributed string pour avoir la premiere lettre d'une nsstring qui s'affiche avec une autre police (taille + couleur) comme sur la capture en PJ.


 


Merci


 


 


Réponses

  • Bien sûr... Un truc de ce genre...



    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@MonTexte];

    [string beginEditing];
    selectedRange = NSMakeRange(0, 3);
    [string addAttribute:NSFontAttributeName
    value:[UIFont boldSystemFontOfSize:15.]
    range:selectedRange];
    selectedRange = NSMakeRange(3, 5);
    [string addAttribute:NSFontAttributeName
    value:[UIFont italicSystemFontOfSize:13.0]
    range:selectedRange];

  • LarmeLarme Membre
    octobre 2014 modifié #3

    Oui.


    De tête, à  une erreur de compil'/warning près :



    NSMutableAttributedString *attributedString = [NSMutableAttributedString alloc] initWithString:stringInitial];
    NSDictionary *effectFirstLetter = @{NSForegroundAttributeName:[UIColor yourGreenColor], NSFontAttributeName:[UIFont fontWithName:yourFontName size:yourSize]};
    [attributedString addAttributes:effectFirstLetter range:NSMakeRange(0,1)]; 

    Vu que la première lettre semble être en gras, il peut être utile de savoir que :

    Italic, Taille et Gras (notamment) sont gérés par le NSFontAttributeName.

    Du coup, il faut que ta police gère ça.


     


    Notamment si j'pense au texte en bas en italic.


  • Vous etes géniaux, merci :)


  • AliGatorAliGator Membre, Modérateur
    octobre 2014 modifié #5
    Je t'invite à  utiliser ma catégorie permettant de facilement manipuler les NSAttributedString sans se perdre dans les addAttribute:value: et permettant d'avoir une API bien plus sympa.
     
    #import "OHAttributedStringAdditions.h"

    // Quote
    NSMutableAttributedString* str = [NSMutableAttributedString attributedStringWithString:@Every man is the architect of its own future.\n\n];
    [str setFont:[UIFont boldSystemFontOfSize:24] range:NSMakeRange(0,1)]; // Bigger first letter
    [str setTextColor:[UIColor greenColor] range:NSMakeRange(0,1)]; // Green first letter

    // Add author in italics: we can also concat 2 attributed strings instead of applying attributes to ranges, that's another way to do it
    NSMutableAttributedString* author = [NSMutableAttributedString attributedStringWithString:@Sallust];
    [author setFontItalics:YES];
    [str appendAttributedString:author];

    // Display in label
    label.attributedText = str;
  • Bon, je l'admet, ma réponse était bien moins précise, mais tout de même Ali, tu faiblis ! 3 réponses avant que tu ne te réveilles !!!  ;D  :-*


  • AliGatorAliGator Membre, Modérateur
    octobre 2014 modifié #7
    Ca s'appelle "avoir du boulot" :D Ouais ça m'arrive de temps en temps ;)
Connectez-vous ou Inscrivez-vous pour répondre.