Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method sizeToFit on a UILabel that has subscripts is not working

I have a subclass of UILabel, which is supposed to update its text when the user types something. Naturally, as the length of text increases, the size of the label must adjust to accommodate the text. I called the sizeToFit method, and while the label adjusts its width correctly, the bottom of the text is cut off. The problem is that the text includes subscripts and superscripts , and the label is not adjusting itself with the subscripts in consideration (for example, with H₂O the bottom of the two is cut off).

Can I override sizeToFit or sizeThatFits: to increase the height of the label?

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]

}
like image 893
Mahir Avatar asked Nov 14 '22 12:11

Mahir


1 Answers

You should override the UILabel method (CGSize)sizeThatFits:(CGSize)size in your subclass like example below. I just add 10pt to the height calculated by UILabel to accommodate the subscript.

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

Sample 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));

From the 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
like image 159
Ken W Avatar answered Nov 16 '22 03:11

Ken W