2013-08-21 5 views
68

NSAttributedString è davvero impenetrabile per me.Esempio di NSAttributedString con due dimensioni di carattere diverse?

Voglio impostare un UILabel per avere testo di dimensioni diverse, e ho capito che NSAttributedString è la strada da percorrere, ma non riesco ad arrivare da nessuna parte con la documentazione su questo.

Mi piacerebbe se qualcuno potesse aiutarmi con un esempio concreto.

Per esempio, diciamo che il testo che volevo era:

(in small letters:) "Presenting The Great..." 
(in huge letters:) "HULK HOGAN!" 

qualcuno può mostrare come fare? O anche, un riferimento che è semplice e semplice dove potrei imparare per me stesso? Giuro che ho cercato di capirlo attraverso la documentazione, e anche attraverso altri esempi su Stack Overflow, e non lo capisco.

risposta

150

Si potrebbe fare qualcosa di simile ...

NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"]; 
[hogan addAttribute:NSFontAttributeName 
       value:[UIFont systemFontOfSize:20.0] 
       range:NSMakeRange(24, 11)]; 

Questo imposterà le ultime due parole nel testo di 20 punti; il resto della stringa utilizzerà il valore predefinito (che credo sia 12 punti). La cosa che potrebbe confondere l'impostazione della dimensione del testo è che devi impostare il carattere e allo stesso tempo: ogni oggetto UIFont incapsula entrambe le proprietà.

+0

Dai un'occhiata a questa risposta per le gamme SWIFT: http://stackoverflow.com/a/27041376/1736679 – Efren

0

Se si vuole fare in modo semplice, c'è un repository git chiamato OHAttributedLabel che io uso che fornisce una categoria su NSAttributedString. Ti permette di fare le cose come:

NSMutableAttributedString *mystring = [[NSMutableAttributedString alloc] initWithString:@"My String"]; 
[mystring setTextColor:[UIColor colorWithRGB:78 green:111 blue:32 alpha:1]]; 
mystring.font = [UIFont systemFontOfSize:14]; 

Se non si desidera utilizzare un terzo partito lib, controlla this link per un tutorial decente su come iniziare con le stringhe attribuiti.

14

Swift 3 Soluzione

Inoltre, è possibile utilizzare la funzione append invece di specificare gli indici in objC o Swift:

let attrString = NSMutableAttributedString(string: "Presenting The Great...", 
              attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 20) ]) 

attrString.append(NSMutableAttributedString(string: "HULK HOGAN!", 
              attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 40) ])) 
1

a Swift 4, si farebbe:

let attrString = NSMutableAttributedString(string: "Presenting The Great...", 
             attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)])); 

attrString.append(NSMutableAttributedString(string: "HULK HOGAN!", 
             attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 36)]));