2013-05-24 12 views
11

È possibile aggiungere allineamenti sinistro e destro a parti diverse della stringa?NSMutableAttributedString aggiungi allineamenti diversi

Ho provato ad aggiungere l'attributo di allineamento alla parte destra:

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init]; 
    [paragrahStyle setAlignment:NSTextAlignmentRight]; 
    [mutableAttributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:rangeOfDate]; 

Ma l'intera stringa è allineato a sinistra.

risposta

36

Quello che fai nel codice è impostare lo stile di paragrafo (il testo da \ n a \ n) e non è possibile avere più allineamenti di testo nello stesso paragrafo. Ho avuto lo stesso problema e ho finito per utilizzare più UILabels in iOS 6 :-(

Tuttavia, in iOS 7 ho notato TabStops per ParagraphStyle, che in realtà lo rende possibile, ma trovo la documentazione abbastanza inadeguata. È possibile impostare un TapStop allineato a destra, che fa sì che il testo venga reso alla sinistra della fermata specificata (fino a quando non viene riempito lo spazio). Per far funzionare il mio semplice esempio, ho dovuto aggiungere a almeno un attributo di più oltre al primo comma - avrebbe potuto essere solo un UIColor chiaro per lo sfondo però :-)

quello che segue è un semplice esempio di drawRect in un UIView:

- (void)drawRect:(CGRect)rect 
{ 
    NSString *str = @"to the left\tto the right\nleft again\tright again"; 
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str]; 

    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; 
    paragraph.maximumLineHeight = 12.0f; 
    paragraph.alignment = NSTextAlignmentLeft; 

    NSTextTab *t = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentRight location:rect.size.width options:nil]; 
    paragraph.tabStops = @[t]; 

    [att addAttribute:NSBackgroundColorAttributeName value:[UIColor magentaColor] range:NSMakeRange(0, @"to the left".length)]; 
    [att addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Trebuchet-BoldItalic" size:12.0] range:NSMakeRange(12, 5)]; 
    [att addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(str.length - 4, 2)]; 
    [att addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, str.length)]; 

    [att drawInRect:rect]; 
} 

Che il codice renderà la seguente:

enter image description here

+0

Fresco e davvero utile! – zetachang

+2

Sono confuso perché, se rimuovo tutti gli attributi oltre a NSParagraphStyleAttributeName, che interrompe la formattazione. È un errore o sto fraintendendo qualcosa? – TomSwift

+0

Sì, sembra un bug per me. L'ho trovato mentre facevo questo: http: // StackOverflow.it/questions/24434552/nstextalignmentcenter-and-nstextalignmentright-are-the-wrong-way-round-in-nstext – jowie

6

Sulla @ risposta di Verglas ...

Il modo che normalmente si fa qualcosa di simile in HTML è via galleggiante. Something like this::

<div><p style='float: left;'>Left</p><p style='float: right;'>Right</p><div style='clear: both;'></div></div> 

Sarebbe bello se si potesse trasformare questo in un NSAttributedString e farlo funzionare:

NSString* html = @"<div><p style='float: left;'>Left</p><p style='float: right;'>Right</p><div style='clear: both;'></div></div>"; 

NSData* d = [html dataUsingEncoding: NSUTF8StringEncoding]; 

NSAttributedString* as = [[NSMutableAttributedString alloc] initWithData: d 
               options: @{ 
                  NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
                  NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding) 
                  } 
            documentAttributes: nil 
               error: nil]; 

Purtroppo, non funziona.

per un secondo tentativo, si può provare a utilizzare una tabella HTML:

html = @"<table style='width:100%'><tr><td>Left</td><td style='text-align:right;'>Right</td></tr></table>"; 

Curiosamente, questo funziona come previsto. La cosa ancora più curiosa sono gli attributi che genera:

2014-08-27 14:27:31.443 testParagraphStyles[2095:60b] range: {0, 5} attributes: { 
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n \"<NSTextTableBlock: 0x8d9c920>\"\n), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; 

2014-08-27 14:27:31.444 testParagraphStyles[2095:60b] range: {5, 6} attributes: { 
    NSParagraphStyle = "Alignment 2, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n \"<NSTextTableBlock: 0x8da1550>\"\n), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; 
} 

Scorrere a destra e notare il riferimento a NSTextTableBlock. NSTextTable non è un'API pubblica su iOS, ma NSAttributoString initWithData: options: documentAttributes: error: utilizzato per generare la stringa attribuita da HTML. Ciò è doloroso perché significa che non possiamo costruire manualmente una NSAttribuitString (dobbiamo generarlo da HTML usando questa API).

La creazione di stringhe attribuite da HTML è lenta e in gran parte non documentata. Lo evito ogni volta che posso.

Problemi correlati