2013-09-22 4 views
45

Nella versione iOS 5 della mia app ho avuto:testo align utilizzando drawInRect: withAttributes:

[self.text drawInRect: stringRect 
      withFont: [UIFont fontWithName: @"Courier" size: kCellFontSize] 
     lineBreakMode: NSLineBreakByTruncatingTail 
      alignment: NSTextAlignmentRight]; 

Sto passando per iOS 7. Il metodo di cui sopra è deprecato. Ora sto usando drawInRect: withAttributes:. Il parametro attributi è un oggetto NSDictionary. Posso ottenere drawInRect: withAttributes: a lavorare per l'ex parametro di carattere utilizza questo:

 UIFont *font = [UIFont fontWithName: @"Courier" size: kCellFontSize]; 

     NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: font, NSFontAttributeName, 
            nil]; 

     [self.text drawInRect: stringRect 
      withAttributes: dictionary]; 

Cosa coppie chiave-valore si aggiunge a dizionario per ottenere NSLineBreakByTruncatingTail e NSTextAlignmentRight?

risposta

136

C'è una chiave per impostare lo stile di paragrafo del testo (inclusa la modalità di interruzione di riga, l'allineamento del testo e altro).

Da docs:

NSParagraphStyleAttributeName

Il valore di questo attributo è un oggetto NSParagraphStyle. Utilizzare questo attributo per applicare più attributi a un intervallo di testo. Se non si specifica questo attributo, la stringa utilizza gli attributi di paragrafo predefiniti, come restituito dal metodo defaultParagraphStyle di NSParagraphStyle.

Quindi, si può provare il seguente:

UIFont *font = [UIFont fontWithName:@"Courier" size:kCellFontSize]; 

/// Make a copy of the default paragraph style 
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
/// Set line break mode 
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; 
/// Set text alignment 
paragraphStyle.alignment = NSTextAlignmentRight; 

NSDictionary *attributes = @{ NSFontAttributeName: font, 
        NSParagraphStyleAttributeName: paragraphStyle }; 

[text drawInRect:rect withAttributes:attributes]; 
+2

Come hai trovato questo? +1 – ViruMax

+0

Anche se non riesco a capire una variazione più breve - questo funziona sicuramente, ma sembra un lavoro da assegnare solo per aggiungere qualche giustificazione! –

+0

Come posso creare una stringa multi linea? –

4

Il codice sta andando in questo modo:

CGRect textRect = CGRectMake(x, y, length-x, maxFontSize); 
UIFont *font = [UIFont fontWithName:@"Courier" size:maxFontSize]; 
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; 


    paragraphStyle.alignment = NSTextAlignmentRight; 
    NSDictionary *attributes = @{ NSFontAttributeName: font, 
            NSParagraphStyleAttributeName: paragraphStyle, 
            NSForegroundColorAttributeName: [UIColor whiteColor]}; 
[text drawInRect:textRect withAttributes:attributes];