2012-01-07 9 views
5

Ho una sottoclasse di UILabel, che dovrebbe aggiornare il testo quando l'utente digita qualcosa. Naturalmente, man mano che la lunghezza del testo aumenta, la dimensione dell'etichetta deve adattarsi al testo. Ho chiamato il metodo sizeToFit, e mentre l'etichetta regola correttamente la sua larghezza, la parte inferiore del testo è tagliata. Il problema è che il testo include pedici e apici, e l'etichetta non si sta adeguando con gli indici in considerazione (per esempio, con H₂O la parte inferiore dei due è tagliata).Metodo di chiamata sizeToFit su un UILabel con pedici non funzionanti

Posso sovrascrivere sizeToFit o sizeThatFits: per aumentare l'altezza dell'etichetta?

EDIT:

- (void) addCompound { 

self.currentLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]; 

[self addSubview:self.currentLabel]; 

[self.currentLabel sizeToFit]; 

// Right now self.currentlabel.text = "". However, I've confirmed thru NSLogging that letters are added to self.currentLabel.text as the user types on the keyboard. Also, the text displays properly (as long as it's within the original frame) when I remove [sel.currentLabel sizeToFit] 

} 
+0

riscrittura sizeToFit e dopo [super sizeToFit]; modifica altezza – SAKrisT

+0

@SAKrisT '- (void) sizeToFit { [super sizeToFit]; self.frame = CGRectMake (self.frame.origin.x, self.frame.origin.y, self.frame.size.width, 100); } ' – Mahir

+1

@SAKrisT Ho provato a farlo ma la vista non appare – Mahir

risposta

2

Si dovrebbe eseguire l'override del metodo UILabel (CGSize) sizeThatFits: (CGSize) formato nella sottoclasse, come nell'esempio qui sotto. Aggiungo solo 10pt all'altezza calcolata da UILabel per contenere l'indice.

@implementation ESKLabel 
- (CGSize)sizeThatFits:(CGSize)size 
{ 
    CGSize theSize = [super sizeThatFits:size]; 
    return CGSizeMake(theSize.width, theSize.height + 10); 
} 
@end 

Esempio di output:

self.eskLabel.text = @"Hello Long² Long\u2082 World"; 
NSLog(@"CGSize: %@", NSStringFromCGSize(self.eskLabel.frame.size)); 
[self.eskLabel sizeToFit]; 
NSLog(@"CGSize: %@", NSStringFromCGSize(self.eskLabel.frame.size)); 

Dal NSLog:

This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 864. 
2012-01-06 23:34:21.949 Stackoverflow4[864:f803] CGSize: {85, 61} 
2012-01-06 23:34:21.951 Stackoverflow4[864:f803] CGSize: {302, 44} 
kill 
quit 
-1

Questo dovrebbe per il trucco:

self.eskLabel.adjustsFontSizeToFitWidth = YES; 
Problemi correlati